计算字符串中特定的字符数

时间:2017-04-17 12:31:54

标签: javascript

我正在尝试计算字符串中特定字符的数量,但是得到“0”而不是正确的输出。我知道有更简单的方法来获得解决方案,但我想知道如何这样做以及我做错了什么。

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");

4 个答案:

答案 0 :(得分:4)

你在for循环中返回,所以forloop只迭代一次:

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");

顺便说一下,更短:

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

答案 1 :(得分:3)

返回计数应该在循环之外的地方

答案 2 :(得分:2)

您可以尝试splitfilter。结果length的{​​{1}}是找到的字符数:

Array
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;
}

答案 3 :(得分:1)

您不小心将return语句放在for循环中,因此它在第一次循环后返回。修正如下:

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");