计算字符串中子字符串的出现次数
计算给定字符串中子字符串的出现次数。
- 使用
Array.prototype.indexOf()在str中查找searchValue。 - 如果找到该值,则增加计数器并更新索引
i。 - 使用
while循环,当Array.prototype.indexOf()返回值为-1时返回计数器。
const countSubstrings = (str, searchValue) => {
let count = 0,
i = 0;
while (true) {
const r = str.indexOf(searchValue, i);
if (r !== -1) [count, i] = [count + 1, r + 1];
else return count;
}
};
countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3
countSubstrings('tutut tut tut', 'tut'); // 4