Go Tutorials

Go Programs

Go Count the Number of Each Vowel


Go Count the Number of Each Vowel

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
}


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,

  1. Import the fmt and strings packages.
  2. Define a function named countVowels that takes one parameter s of type string.
  3. Initialize a string vowels containing all vowel characters.
  4. Initialize a map vowelCount to store the count of each vowel.
  5. Use a for loop to iterate through the characters of the input string.
  6. In each iteration, check if the character is a vowel using strings.ContainsRune. If true, increment the count in the map.
  7. Return the map of vowel counts.
  8. 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]