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

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)


// 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.

func countNonOverlapping(haystack string, needle string) int {
    /*
       Count how many times 'needle' appears in 'haystack' without overlapping.
       The algorithm:
         • Use strings.Index() 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.
    */

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

    // Continue searching until Index returns -1 (meaning: no more matches)
    for {
        // Find the next occurrence starting at the current index
        pos := strings.Index(haystack[index:], needle)

        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 + len(needle)
    }

    return count
}


// ---------------------------------------------------------------
func main() {
    // Demonstration using the string provided in the instructions:
    s := "go java phphp rust c pphpp c++ phpphp python php phphp"
    substring := "php"

    // Count non-overlapping occurrences
    result := countNonOverlapping(s, substring)

    fmt.Println("Non-overlapping occurrences:", result)
}


/*
run:

Non-overlapping occurrences: 6

*/

 



answered Aug 19, 2020 by avibootz
edited 6 hours ago by avibootz

Related questions

...