Rassisland
Rassisland

Reputation: 167

counting specific number of characters in a string

I'm trying to count the number of specific characters in a string, but am getting "0" instead of the correct output. I know there are easier ways to get the solution, but I want to know how to do it this way and what I'm doing wrong.

function countCharacter(str, char) {
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char){
      count++;
    }
    return count;
  }
}
countCharacter("My cat is driving my crazy", "a");

Upvotes: 1

Views: 357

Answers (4)

KooiInc
KooiInc

Reputation: 122898

You can try split and filter. The length of the resulting Array is the number of found characters:

const aFound = "My cat is driving my crazy"
  .split("")                     // split per character
  .filter( chr => chr === "a" ); // filter on character 'a'

const numberOfz = findCharacterInString("I'm driving my cat crazy", "z");

document.querySelector("pre").textContent = `
  There is/are ${aFound.length} a('s) in "My cat is driving my crazy"
  There is/are ${numberOfz} z('s) in "I'm driving my cat crazy"`;
  
// As method (case insensitive)
function findCharacterInString(string2Search, character) {
  return string2Search
    .split("")
    .filter( chr => chr.toLowerCase() === character.toLowerCase() )
    .length;
}
<pre></pre>

Upvotes: 2

Alexander Nied
Alexander Nied

Reputation: 13623

You accidentally put your return statement inside your for loop, so it returns after the first time it runs through the loop. Fixed below:

function countCharacter(str, char) {
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char){
      count++;
    }
  }
  return count;
}
countCharacter("My cat is driving my crazy", "a");

Upvotes: 1

Dzmtrs
Dzmtrs

Reputation: 446

Return count should be in a place out of the loop

Upvotes: 3

Jonas Wilms
Jonas Wilms

Reputation: 138247

Youre returning in the for loop, so the forloop just iterates once:

function countCharacter(str, char) {
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char){
      count++;
    }
  }
 return count;
}
countCharacter("My cat is driving my crazy", "a");

By the way, shorter:

countCharacter=(str,char)=>str.split("").reduce((count,letter)=>letter===char?count+1:count,0);

Upvotes: 4

Related Questions