Quantcast
Viewing latest article 11
Browse Latest Browse All 43

Answer by Michel for How to count string occurrence in string?

Iterate less the second time (just when first letter of substring matches) but still uses 2 for loops:

   function findSubstringOccurrences(str, word) {        let occurrences = 0;        for(let i=0; i<str.length; i++){            if(word[0] === str[i]){ // to make it faster and iterate less                for(let j=0; j<word.length; j++){                    if(str[i+j] !== word[j]) break;                    if(j === word.length - 1) occurrences++;                }            }        }        return occurrences;    }    console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));

Viewing latest article 11
Browse Latest Browse All 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>