Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Count instances of substring in a string in Go (Golang)

Posted on March 12, 2023March 12, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a Count method that can be used to get the number of non-overlapping instances of a substring in a particular string.
Below is the signature of the function

func Count(s, substr string) int


Also note that if the substr supplied to the function is an empty string, then return value will be 1+ count of Unicode Code points in the given string.

Let’s look at the working code


Code:

package main
import (
"fmt"
"strings"
)
func main() {
//Case 1 Input string contains the substring
res := strings.Count("abcdabcd", "ab")
fmt.Println(res)
//Case 1 Input string doesn't contains the substring
res = strings.Count("abcdabcd", "xy")
fmt.Println(res)
//Case 1 Substring supplied is an empty string
res = strings.Count("abcdabcd", "")
fmt.Println(res)
}

Output:

2
0
9

Recent Posts

  • Find the index of the first instance of a substring in Go (Golang)
  • Count instances of substring in a string in Go (Golang)
  • Trim leading and trailing whitespaces from a string in Go (Golang)
  • Trim suffix of a string in Go (Golang)
  • Trim prefix of a string in Go (Golang)
©2023 Welcome To Golang By Example | Design: Web XP