YuArtian/blog

字符串查找计数

Opened this issue · 0 comments

字符串查找计数

Create a function called that accepts 2 string arguments and returns an integer of the count of occurrences the 2nd argument is found in the first one.

If no occurrences can be found, a count of 0 should be returned.

strCount('Hello', 'o') // => 1
strCount('Hello', 'l') // => 2
strCount('', 'z')      // => 0

Notes:

  • The first argument can be an empty string
  • The second string argument will always be of length 1

牛皮写法 the best

function strCount(str, letter){  
  return str.split(letter).length - 1
}

一般

function strCount(str, letter){  
  return str.split('').filter(c => c == letter).length;
}

菜逼写法

function strCount(str, letter){  
  if(str==='') return 0
  let count = 0;
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] == letter)
      count++;
  }
  
  return count;
  
}