网络知识 娱乐 碎片时间学编程「103]:计算字符串的子串

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


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

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

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

JavaScript

const countSubstrings = (str, searchValue) => {n let count = 0,n i = 0;n while (true) {n const r = str.indexOf(searchValue, i);n if (r !== -1) [count, i] = [count + 1, r + 1];n else return count;n }n};

示例

countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3ncountSubstrings('tutut tut tut', 'tut'); // 4nn

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