Quantcast
Channel: How to count string occurrence in string? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

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

$
0
0

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 all articles
Browse latest Browse all 43

Trending Articles



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