Menu Close

Go – Count the total number of substring in string in go golang

Here, We are going to learn about counting the total number of substring in string in go golang. We can get the count by using Count() function of strings package in go golang.

Function prototype:

func Count(str string, substr string) int

Return value:

Count() function counts the number of non-overlapping instances of substr in str.
If substr is an empty string, Count() function returns (1 + the number of Unicode code points in str).

Example:

string = "HelloTechHelloTechHelloTech"
sub_str = "Tech"

Here, "Tech" substring present 3 times in string "HelloTechHelloTechHelloTech". So strings.Count() function will return 3. 

Example with program:

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Tech are repeated 3 times in "HelloTechHelloTechHelloTech" string
	str := "HelloTechHelloTechHelloTech"
	sub_str := "Tech"
	fmt.Println(strings.Count(str, sub_str))
	
	// there are 3 times 'e' in 'cheese'
	fmt.Println(strings.Count("cheese", "e"))
	
	fmt.Println(strings.Count("five", ""))
	
	// there are 1 times 's' in 'cheese'
	fmt.Println(strings.Count("cheese", "s"))
	
	// there are 2 times 'wi' in 'JohnwickJohnwick'
	fmt.Println(strings.Count("JohnwickJohnwick", "wi"))
}

Output:

3
5
1
2

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/pkg/

Posted in golang, packages, strings

Leave a Reply

Your email address will not be published. Required fields are marked *