Open In App
Related Articles

How to Count the Number of Repeated Characters in a Golang String?

Like Article
Save Article
Report issue
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go string, you can count some specific Unicode code points or the number of non-overlapping instances of costr (Repeated Characters) in the string with the help of Count() function. This function returns a value which represents the total number of the given string or Unicode code points present in the string. It is defined under the strings package so, you have to import strings package in your program for accessing Count function. Syntax:
func Count(str, costr string) int
Here, str is the original string and costr is a string which we want to count. If the value of costr is empty, then this function returns 1 + the number of Unicode code points in str. Example:
// Go program to illustrate how to
// count the elements of the string
package main
import (
// Main function
func main() {
    // Creating and initializing the strings
    str1 := "Welcome to the online portal of GeeksforGeeks"
    str2 := "My dog name is Dollar"
    str3 := "I like to play Ludo"
    // Displaying strings
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
    fmt.Println("String 3: ", str3)
    // Counting the elements of the strings
    // Using Count() function
    res1 := strings.Count(str1, "o")
    res2 := strings.Count(str2, "do")
    // Here, it also counts white spaces
    res3 := strings.Count(str3, "")
    res4 := strings.Count("GeeksforGeeks, geeks", "as")
    // Displaying the result
    fmt.Println("\nResult 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
    fmt.Println("Result 4: ", res4)

String 1:  Welcome to the online portal of GeeksforGeeks
String 2:  My dog name is Dollar
String 3:  I like to play Ludo

Result 1:  6
Result 2:  1
Result 3:  20
Result 4:  0

Last Updated : 26 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Similar Reads