Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

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

Posted on March 12, 2020March 12, 2020 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
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme