Count the Number of Each Vowel in Go
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.
What is String Manipulation
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.
Syntax
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
}
Example 1: Counting the number of each vowel in a string
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,
- Import the
fmt
andstrings
packages. - Define a function named
countVowels
that takes one parameters
of typestring
. - Initialize a string
vowels
containing all vowel characters. - Initialize a map
vowelCount
to store the count of each vowel. - Use a
for
loop to iterate through the characters of the input string. - In each iteration, check if the character is a vowel using
strings.ContainsRune
. If true, increment the count in the map. - Return the map of vowel counts.
- In the main function, call the
countVowels
function with a sample string and print the result.
Go Program
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)
}
Output
Vowel counts: map[A:0 E:2 I:0 O:4 U:0 a:0 e:2 i:0 o:4 u:0]