Go count occurrences of a substring

To count the occurrences of a substring in Go, you can follow these steps:

  1. Import the necessary packages: Import the "strings" package to work with strings.

  2. Declare the main function: Start by declaring the main function, which is the entry point of the program.

  3. Define the string and substring: Declare a variable to store the string in which you want to count the occurrences, and another variable to store the substring you want to search for.

  4. Use the strings.Count() function: Call the strings.Count() function and pass in the string and substring as arguments. This function returns the number of non-overlapping instances of the substring within the string.

  5. Print the result: Print the result to the console using the fmt.Println() function.

Here is an example code snippet that demonstrates how to count occurrences of a substring in Go:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, hello, hello, world!"
    substr := "hello"

    count := strings.Count(str, substr)

    fmt.Println("Occurrences:", count)
}

In this example, the substring "hello" occurs three times in the string "Hello, hello, hello, world!". The output will be:

Occurrences: 3