7-3 统计字符出现次数
原题:
统计并输出某给定字符在给定字符串中出现的次数。
输入格式:
输入第一行给出一个以回车结束的字符串(少于80个字符);第二行输入一个字符。
输出格式:
在一行中输出给定字符在给定字符串中出现的次数。
.
解题思路:
解题思路:创建统计字符方法,返回结果
JavaScript(node)代码:
const r = require("readline");
const rl = r.createInterface({
input:process.stdin,
output: process.stdout
});
rl.question('',(str)=>{
rl.question('',(char)=>{
console.log(`${
countChar(str,char)}`);
rl.close();
})
});
//方法一:
// function countChar(str,char){
// let count = 0;
// for(let i =0; i<str.length;i++){
// if(str[i]==char){
// count++;
// }
// }
// return count;
// }
//方法二:
// function countChar(str, char) {
// let count = 0;
// for (let ch of str) {
// if (ch === char) {
// count++;
// }
// }
// return count;
// }
//方法三:
function countChar(str, char) {
return Array.from(str).reduce((count, ch) => (ch === char) ? count + 1 : count, 0);
}
.