Data Structure
 Networking
 RDBMS
 Operating System
 Java
 MS Excel
 iOS
 HTML
 CSS
 Android
 Python
 C Programming
 C++
 C#
 MongoDB
 MySQL
 Javascript
 PHP
- Selected Reading
 - UPSC IAS Exams Notes
 - Developer's Best Practices
 - Questions and Answers
 - Effective Resume Writing
 - HR Interview Questions
 - Computer Glossary
 - Who is Who
 
How to count the number of repeated characters in a Golang String?
Count() is a built-in function is Golang that can be used to count the number of non-overlapping instances of a character/string in a string.
Syntax
func Count(s, sep string) int
Where,
s – Original String
sep – Substring which we want to count.
It returns an Integer value.
Example
The following example demonstrates how you can use the Count() function in a Go program.
package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   x := "Golang Programming Language"
   y := "Language"
  
    // Display the Strings
   fmt.Println("First String:", x)
   fmt.Println("Second String:", y)
   
   // Using Count Function
   test1 := strings.Count(x, "g")
   test2 := strings.Count(y, "b")
   
   // Diplay the Count Output
   fmt.Println("Count of 'g' in the First String:", test1)
   fmt.Println("Count of 'b' in the Second String:", test2)
}
Output
On execution, it will produce the following output −
First String: Golang Programming Language Second String: Language Count of 'g' in the First String: 5 Count of 'b' in the Second String: 0
Example
Let us take another example −
package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   p := "Hyderabad"
   q := "Country"
   r := "Chennai"
   s := "Pune"
   
   // Display the Strings
   fmt.Println("First String:", p)
   fmt.Println("Second String:", q)
   fmt.Println("Third String:", r)
   fmt.Println("Fourth String:", s)
   
   // Using the Count Function
   w := strings.Count(p, "d")
   x := strings.Count(q, "t")
   y := strings.Count(r, "n")
   z := strings.Count(s, "e")
  
   // Display the Count Output
   fmt.Println("Count of 'd' in First String:", w)
   fmt.Println("Count of 't' in Second String:", x)
   fmt.Println("Count of 'n' in Third String:", y)
   fmt.Println("Count of 's' in Fourth String:", z)
}
Output
It will produce the following output −
First String: Hyderabad Second String: Country Third String: Chennai Fourth String: Pune Count of 'd' in First String: 2 Count of 't' in Second String: 1 Count of 'n' in Third String: 2 Count of 's' in Fourth String: 1
Advertisements