In this exercise, you'll learn how to count vowels in a string using Go. You'll work with loops, conditions, and string manipulation.
1. Read a string input from the user.
2. Iterate through each character in the string.
3. Check if the character is a vowel (A, E, I, O, U, a, e, i, o, u).
4. Count and display the number of vowels found.
5. Display the vowels detected.
for range
.aeiouAEIOU
) and check if a character belongs to this list.strings.TrimSpace()
.strings.ContainsRune()
: This function is ideal for checking if a character is inside a string.package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the phrase: ")
s, _ := reader.ReadString('\n')
s = strings.TrimSpace(s) // Remove spaces and newline characters
vowels := "aeiouAEIOU" // List of vowels
count := 0 // Vowel counter
foundVowels := "" // Store found vowels
// Iterate through each character and identify vowels
for _, char := range s {
if strings.ContainsRune(vowels, char) {
count++
foundVowels += string(char) + " " // Add vowel with a space
}
}
fmt.Printf("Number of vowels: %d\n", count)
fmt.Printf("Vowels found: %s\n", foundVowels)
}
bufio
for reading input, os
for standard input, and strings
for string operations.bufio.NewReader(os.Stdin).ReadString('\n')
is used to read the full user input, including spaces.strings.TrimSpace(s)
removes unnecessary spaces or newlines.for _, char := range s
to check each character.strings.ContainsRune(vowels, char)
checks if the character is a vowel.count
.foundVowels
to display them later.Enter the phrase: Hello World
Number of vowels: 3
Vowels found: e o o
🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊