寻找特定字母在 JavaScript 语句中出现的次数
我们需要编写一个 JavaScript 函数,该函数查找特定字母在语句中出现的次数。
举例说明
代码如下 −
const string = 'This is just an example string for the program';
const countAppearances = (str, char) => {
let count = 0;
for(let i = 0; i < str.length; i++){
if(str[i] !== char){
// using continue to move to next iteration
continue;
};
// if we reached here it means that str[i] and char are same
// so we increase the count
count++;
};
return count;
};
console.log(countAppearances(string, 'a'));
console.log(countAppearances(string, 'e'));
console.log(countAppearances(string, 's'));输出
控制台中的输出 −
3 3 4
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP