diff --git a/snippets/countSubstrings.md b/snippets/countSubstrings.md new file mode 100644 index 000000000..cefd26190 --- /dev/null +++ b/snippets/countSubstrings.md @@ -0,0 +1,27 @@ +--- +title: countSubstrings +tags: string,algorithm,beginner +--- + +Counts the occurences of a substring in a given string. + +- Use `Array.prototype.indexOf()` to look for `searchValue` in `str`. +- Increment a counter if the value is found and update the index, `i`. +- Use a `while` loop that will return as soon as the value returned from `Array.prototype.indexOf()` is `-1`. + +```js +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; + } +}; +``` + +```js +countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3 +countSubstrings('tutut tut tut', 'tut'); // 4 +``` diff --git a/snippets/indexOfSubstrings.md b/snippets/indexOfSubstrings.md new file mode 100644 index 000000000..cd926c703 --- /dev/null +++ b/snippets/indexOfSubstrings.md @@ -0,0 +1,29 @@ +--- +title: indexOfSubstrings +tags: string,algorithm,generator,intermediate +--- + +Finds all the indexes of a substring in a given string. + +- Use `Array.prototype.indexOf()` to look for `searchValue` in `str`. +- Use `yield` to return the index if the value is found and update the index, `i`. +- Use a `while` loop that will terminate the generator as soon as the value returned from `Array.prototype.indexOf()` is `-1`. + +```js +const indexOfSubstrings = function* (str, searchValue) { + let i = 0; + while (true) { + const r = str.indexOf(searchValue, i); + if (r !== -1) { + yield r; + i = r + 1; + } else return; + } +}; +``` + +```js +[...indexOfSubstrings('tiktok tok tok tik tok tik', 'tik')]; // [0, 15, 23] +[...indexOfSubstrings('tutut tut tut', 'tut')]; // [0, 2, 6, 10] +[...indexOfSubstrings('hello', 'hi')]; // [] +```