In Golang, you can count the number of occurrences of a character in a string by iterating over each character in the string and checking if it matches the desired character. Here's an example:
package main
import (
"fmt"
"strings"
)
func countOccurrences(str, char string) int {
count := 0
for _, c := range str {
if string(c) == char {
count++
}
}
return count
}
func main() {
str := "Hello, world!"
char := "o"
count := countOccurrences(str, char)
fmt.Printf("Number of occurrences of %s in \"%s\" : %d\n", char, str, count)
// Alternatively, you can use strings.Count() function
count2 := strings.Count(str, char)
fmt.Printf("Number of occurrences using strings.Count: %d\n", count2)
}
In this example, the countOccurrences
function takes two parameters - str
is the input string and char
is the character to count occurrences of. It iterates over each character in str
and checks if it matches char
. If it does, the count
variable is incremented. Finally, the function returns the total count.
In the main
function, we demonstrate the usage of the countOccurrences
function. We count the occurrences of the character "o" in the string "Hello, world!". The result is printed to the console. Additionally, we show an alternative way to count occurrences using the strings.Count()
function provided by the standard library.