본문 바로가기
기초다지기/Flutter&Dart

[dart] 문자열 중복 카운트 구하기

by 김빵그 2023. 4. 17.
  • 배열 ["a","a","b","b","c"]... 같은 배열내 중복 카운트 구하기
  • a : 2 , b: 2 , c :1 (a는 2개, b는 2개, c는 1개) 

1. 먼저 문자열을 배열로 만들어 준다. split("")사용

void main() {
  String paragragh =
      "There are many variations of passages of Lorem Ipsum available,
      but the majority have suffered alteration in some form, 
      by injected humour, or randomised words 
      which don't look even slightly believable";
  var list = paragragh.split("");
  print(list);
} 
[T, h, e, r, e,  , a, r, e,  , m, a, n, y,  , v, a, r, i, a, t, i,.....]

2. 값을 담을 map을 빈값으로 만든다 

  • string chr  : int 갯수를 빈값을 만들어준다
 final charCount = <String, int>{};

3. for 문 사용

 for (var chr in list) {
    charCount[chr] = (charCount[chr] ?? 0) + 1;
  }
  
  print(charCount);
  
 //{T: 1, h: 7, e: 20, r: 12,  : 30, a: 15, m: 8, n: 8, y: 4, v: 5, i: 11, t: 9, o: 15, s: 10, f: 5, p: 2, g: 2, L: 1, I: 1, u: 5, l: 8, b: 5, ,: 3, j: 2, d: 6, c: 2, w: 2, ': 1, k: 1}
  • [T, h, e, r, e, ...] list를 하나씩 for문으로 돌린후
  • null 대신 ?? 연산자를 사용하여  charCount[chr] null일경우 0을 아니면 1을 반환하여 업데이트

 

 


전체 코드

 String paragraph =
      "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable";
  var list = paragraph.split("");
  final charCount = <String, int>{};
  for (var chr in list) {
    charCount[chr] = (charCount[chr] ?? 0) + 1;
  }

  print(charCount);

- 자바스크립트 사용시 비슷하게 구현하면 된다

const paragraph =
  "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable";
const list = paragraph.split('');
const charCount = {};

for (const chr of list) {
  charCount[chr] = (charCount[chr] ?? 0) + 1;
}

console.log(charCount);