In this tutorial, we will learn how to count the number of each vowel in a string in Go. We will cover the basic concept of string manipulation and implement a function to perform the counting.
String manipulation involves altering, parsing, and analyzing strings in various ways. Counting the number of each vowel in a string is a common task in text processing.
The syntax to count the number of each vowel in a string in Go is:
import (
"fmt"
"strings"
)
func countVowels(s string) map[rune]int {
vowels := "aeiouAEIOU"
vowelCount := make(map[rune]int)
for _, char := range s {
if strings.ContainsRune(vowels, char) {
vowelCount[char]++
}
}
return vowelCount
}
We can create a function to count the number of each vowel in a given string by iterating through its characters and checking if they are vowels.
For example,
fmt
and strings
packages.countVowels
that takes one parameter s
of type string
.vowels
containing all vowel characters.vowelCount
to store the count of each vowel.for
loop to iterate through the characters of the input string.strings.ContainsRune
. If true, increment the count in the map.countVowels
function with a sample string and print the result.package main
import (
"fmt"
"strings"
)
func countVowels(s string) map[rune]int {
vowels := "aeiouAEIOU"
vowelCount := make(map[rune]int)
for _, char := range s {
if strings.ContainsRune(vowels, char) {
vowelCount[char]++
}
}
return vowelCount
}
func main() {
// Sample string
sampleString := "Hello, world! Welcome to Go programming."
// Count the number of each vowel in the sample string
result := countVowels(sampleString)
// Print the result
fmt.Println("Vowel counts:", result)
}
Vowel counts: map[A:0 E:2 I:0 O:4 U:0 a:0 e:2 i:0 o:4 u:0]