Exercise: Count the Number of Vowels in a String

In this exercise, you'll learn how to count vowels in a string using Go. You'll work with loops, conditions, and string manipulation.

Exercise Objectives:

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.

Tips and Advice

  • Use a loop: Since a string is a sequence of characters, you can loop through it with for range.
  • Use a vowel reference: Store all vowels in a string (aeiouAEIOU) and check if a character belongs to this list.
  • Trim spaces: User input may contain trailing spaces or newlines, so use strings.TrimSpace().
  • Use strings.ContainsRune(): This function is ideal for checking if a character is inside a string.

Correction

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)
}

Explanation of the Solution

  • Imports: We use bufio for reading input, os for standard input, and strings for string operations.
  • Reading input: bufio.NewReader(os.Stdin).ReadString('\n') is used to read the full user input, including spaces.
  • Trimming spaces: strings.TrimSpace(s) removes unnecessary spaces or newlines.
  • Looping: We iterate over the string with for _, char := range s to check each character.
  • Checking vowels: strings.ContainsRune(vowels, char) checks if the character is a vowel.
  • Counting: If a vowel is found, we increment count.
  • Storing vowels: We add found vowels to foundVowels to display them later.

Expected Output:

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! ☕😊


☕ Buy me a coffee