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:
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "Welcome to the online portal of GeeksforGeeks"
str2 := "My dog name is Dollar"
str3 := "I like to play Ludo"
fmt.Println( "String 1: " , str1)
fmt.Println( "String 2: " , str2)
fmt.Println( "String 3: " , str3)
res1 := strings.Count(str1, "o" )
res2 := strings.Count(str2, "do" )
res3 := strings.Count(str3, "" )
res4 := strings.Count( "GeeksforGeeks, geeks" , "as" )
fmt.Println( "\nResult 1: " , res1)
fmt.Println( "Result 2: " , res2)
fmt.Println( "Result 3: " , res3)
fmt.Println( "Result 4: " , res4)
}
|
Output:
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