碎片时间学编程「103]:计算字符串的子串


碎片时间学编程「103]:计算字符串的子串

计算给定字符串中子字符串的出现次数。

  • Array.prototype.indexOf() 函数在字符串中查找 searchValuestr。
  • 如果找到值并更新索引,则增加一个计数器i
  • 使用一个while循环,一旦Array.prototype.indexOf()返回的值为 -1 就会返回。

JavaScript

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

更多内容请访问我的网站:https://www.icoderoad.com

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章