Count the Number of Vowels in a Given String
This program counts the number of vowels (a, e, i, o, u) in a given string using the Go programming language. Below is the complete code with an explanation of its structure.
Go Program
// Package main defines the entry point for the program
package main
// Importing the fmt package for formatted I/O
import (
"fmt"
"strings"
)
// Function countVowels takes a string input and returns the count of vowels in it
func countVowels(s string) int {
// Variable to hold the count of vowels
count := 0
// Convert the string to lowercase to make the function case-insensitive
s = strings.ToLower(s)
// Loop through each character in the string
for _, char := range s {
// Check if the character is a vowel
if char == 'a' || char == 'e' || char == 'i' || char == 'o' || char == 'u' {
// Increment the count if a vowel is found
count++
}
}
// Return the total count of vowels
return count
}
// Main function is the entry point of the program
func main() {
// Example string to count vowels
str := "Hello, World!"
// Call countVowels function and store the result
result := countVowels(str)
// Print the result
fmt.Printf("The number of vowels in '%s' is: %d\n", str, result)
}
Explanation
- Package main: Defines the entry point of the Go program.
- Import fmt and strings: Imports necessary packages for formatted I/O and string manipulation.
- Function countVowels: Takes a string as input, converts it to lowercase, and iterates through each character to count the vowels.
- Variable count: Stores the number of vowels found in the string.
- strings.ToLower(s): Converts the input string to lowercase to make vowel counting case-insensitive.
- for _, char := range s: Iterates through each character in the string.
- If condition: Checks if the character is a vowel and increments the count if true.
- Return count: Returns the total count of vowels found in the string.
- Function main: The entry point of the program that calls countVowels with an example string and prints the result.
Usage
To run the program, save the code in a file with a .go
extension and execute it using the Go compiler:
$ go run filename.go
The program will output the number of vowels in the given string.