查找字符串中某个字符出现的次数
查找字符串中某个字符出现的次数算法逻辑:核心算法:先查找第一个字符出现的位置然后只要indexOf返回的结果不是-1就继续往后查找因为indexOf只能查找到第一个,所以后面的查找,一定是当前索引加1,从而继续向下查找测试function find(str) {let subscript = str.indexOf('o'),i = 0;//定义一个计数器while (subscript !==
·
查找字符串中某个字符出现的次数
算法逻辑:
- 核心算法:先查找第一个字符出现的位置
- 然后只要
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
更多推荐
已为社区贡献1条内容
所有评论(0)