查找字符串中某个字符出现的次数

算法逻辑:

  • 核心算法:先查找第一个字符出现的位置
  • 然后只要indexOf返回的结果不是 -1 就继续往后查找
  • 因为indexOf只能查找到第一个,所以后面的查找,一定是当前索引加1,从而继续向下查找

测试

function find(str, o) {
    let subscript = str.indexOf(o),
        i = 0;//定义一个计数器
    while (subscript !== -1) {
        console.log('str中' + o + '出现的位置有:' + subscript);
        i++;
        subscript = str.indexOf(o, subscript + 1);// `indexOf`只能查找到第一个,所以后面的查找,一定是当前索引加1,从而继续向下查找
    }
    console.log('出现的次数为:' + i);
}

find('abcoefoxyozzopp', 'o');
console.log('====================');
// # 返回数组中元素出现的位置和次数
find([48, 80, 99, 60, 33, 12, 22, 35, 24, 99], 99);
console.log('====================');
// let Arr = ['red', 'blue', 'red', 'green', 'pink', 'red'];
find(['red', 'blue', 'red', 'green', 'pink', 'red'], 'red');

结果

str中o出现的位置有:3
str中o出现的位置有:6
str中o出现的位置有:9
str中o出现的位置有:12
出现的次数为:4
====================
str中99出现的位置有:2
str中99出现的位置有:9
出现的次数为:2
====================
str中red出现的位置有:0
str中red出现的位置有:2
str中red出现的位置有:5
出现的次数为:3
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐