How to count the number of non-overlapping instances of a substring in a string in TypeScript

3 Answers

0 votes
function countNonOverlappingOccurrences(str: string, substr: string) {
    if (substr === "") return 0;
  
    let count: number = 0;
    let offset: number = str.indexOf(substr);
  
    while (offset !== -1) {
        count++;
        offset = str.indexOf(substr, offset + substr.length);
    }
  
    return count;
}
  
const s: string = "phptypescript go java phphp rust c pphpp c++ phpphp python php phphp";
  
console.log(countNonOverlappingOccurrences(s, "php"));
  
  
     
/*
run:
     
7
  
*/

 



answered Aug 25, 2024 by avibootz
edited 4 hours ago by avibootz
0 votes
function countNonOverlappingOccurrences(str: string, substr: string) {
    return (str.length - str.replace(new RegExp(substr, "gi"), "").length) / substr.length;
}
  
const s: string = "phptypescript go java phphp rust c pphpp c++ phpphp python php phphp";
  
console.log(countNonOverlappingOccurrences(s, "php"));
  
  
     
/*
run:
     
7
  
*/
  

 



answered Aug 25, 2024 by avibootz
edited 4 hours ago by avibootz
0 votes
// Non‑overlapping occurrences are matches of a substring that do not reuse any of
// the same characters. Once one match is counted, the next search must begin
// after that match ends.

function count_non_overlapping(haystack: string, needle: string): number {
    /*
       Count how many times 'needle' appears in 'haystack' without overlapping.
       The algorithm:
         • Use indexOf() to locate the next occurrence.
         • Each time a match is found, move the search index forward
           by the full length of the matched substring.
         • This ensures no characters are reused between matches.
    */

    let count: number = 0;
    let index: number = 0;  // current search position in the main string

    // Continue searching until indexOf() returns -1 (meaning: no more matches)
    while (true) {
        // Find the next occurrence starting at the current index
        const pos: number = haystack.indexOf(needle, index);

        if (pos === -1) {
            // No more matches found
            break;
        }

        // We found a match, so increment the count
        count++;

        // Move index forward by the length of the needle
        // This ensures the next search begins *after* the matched substring
        index = pos + needle.length;
    }

    return count;
}


// ---------------------------------------------------------------
// Demonstration using the string provided in the instructions:
const s: string = 'phptypescript go java phphp rust c pphpp c++ phpphp python php phphp';
const substring: string = 'php';

// Count non-overlapping occurrences
const result: number = count_non_overlapping(s, substring);

console.log("Non-overlapping occurrences:", result);


/*
run:

Non-overlapping occurrences: 7

*/

 



answered 4 hours ago by avibootz

Related questions

...