본문 바로가기
알고리즘/Codewars

[Codewars] Vowel Count

by 줍 2024. 6. 3.

Q. Return the number (count) of vowels in the given string.

We will consider a, e, i, o, u as vowels for this Kata (but not y).

The input string will only consist of lower case letters and/or spaces.

 

S. 스위프트에서는 for문에서 문자열 순회가 가능한 반면 다트에서는 Iterable 타입만을 순회할 수 있다고 한다.

split() 함수를 이용해 Iterable하게 만들어주었다.

int getCount(String inputStr) {
  final List<String> vowels = ['a', 'e', 'i', 'o', 'u'];
  int count = 0;
  for (final str in inputStr.split('')) {
    count += vowels.contains(str) ? 1 : 0
  }
  return count;
}

 

+

가장 많은 클레버를 받은 풀이이다. 다트에는 정규 표현식이라는 문자열의 패턴을 표현하는 형식 언어가 있다고 한다.

정규식은 문자열에서 특정 패턴을 검색, 치환하는 등 다양한 문자열 처리 작업에 사용된다.

core 라이브러리에 내장되어 있고, 이 정규식을 다루는 클래스가 RegExp이다. 패턴을 파라미터로 받는다.

allMatches('대상 문자열') 메서드는 패턴과 일치하는 부분을 찾아 이를 Match 타입 객체들의 Iterable로 반환한다.

int getCount(String str) => new RegExp('[aeiou]').allMatches(str).length;

 

정규 표현식 내용이 많지만 문자열 관련 문제에서 자주 보게될 것 같으니 천천히 하나씩 익혀가야겠다.

'알고리즘 > Codewars' 카테고리의 다른 글

[Codewars] Get the Middle Character  (0) 2024.06.04
[Codewars] Sum of positive  (1) 2024.06.03
[Codewars] Return Negative  (0) 2024.06.03
[Codewars] Descending Order  (0) 2024.06.03
[Codewars] Even or Odd  (0) 2024.06.03