JavaScript 단어 알파벳 세어주는 함수

조회수 1137회
 // 주어진 단어(word)에 특정 알파벳(ch)이 몇 번 들어가는지 세어주는 함수
    function countCharacter(word, ch) {
      var count = 0;
      var res = word.toUpperCase();
      var count = res.indexOf(ch);
      if(count === -1){
        count = 0;
      } else if (count >= 0) {
        count = 1;
        count++;
      }
      return count;
    }
  // 단어 word에 알파벳 'A'가 몇 번 나오는지 세어주는 함수
    function countA(word) {
      var count = 1;
      var str = word.toUpperCase();
      for(count; count < str.length; count++){
        return str.indexOf('A');
      }
      return count;
    }
    console.log(countCharacter('AbaCedEAeeee', 'E'));    //2
    console.log(countCharacter('AbaCedEA', 'X'));            //0
    console.log(countA('AbaCedEA'));                                //0

countA함수호출에서 결과가 0이 아니라 3이 나오게 하고싶은데 어떻게 해야 할까요??

1 답변

  • 작성하신 두 함수 모두 다 로직이 틀렸어요.

    indexOf함수는 예외처리를 위해서 쓴 것일 뿐, 핵심이 아닙니다. 함수 내에 반복문 하나면 충분해요.

    function countCharacter(word, ch) {
      var count = 0;
      word = word.toUpperCase();
      ch = ch.toUpperCase();
    
      for (var i = 0; i < word.length; i++) {
        if (word[i] === ch) {
          count++;
        }
      }
      return count;
    }
    
    function countA (word) {
      countCharacter(word, 'a');
    }
    

    단순히 갯수만 구하는거면 아래의 방법도 생각해 볼 수 있겠네요.

    function countCharacter (word, ch) {
      return word.length - word.toUpperCase().split(ch.toUpperCase()).join('').length;
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)