ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Count Vowels in String

Go

Goal -- WPM

Ready
Exercise Algorithm Area
1package main
2
3import "fmt"
4
5// isVowel checks if a character is a vowel (case-insensitive).
6func isVowel(char byte) bool {
7 switch char {
8 case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
9 return true
10 default:
11 return false
12 }
13}
14
15// countVowels counts the number of vowels in a string.
16// It iterates through the string and uses the isVowel helper function.
17func countVowels(s string) int {
18 vowelCount := 0
19
20 // Handle empty string edge case.
21 if len(s) == 0 {
22 return 0
23 }
24
25 for i := 0; i < len(s); i++ {
26 if isVowel(s[i]) {
27 vowelCount++
28 }
29 }
30
31 return vowelCount
32}
33
34func main() {
35 str1 := "Hello World"
36 fmt.Printf("Vowel count in \"%s\": %d\n", str1, countVowels(str1))
37
38 str2 := "AEIOUaeiou"
39 fmt.Printf("Vowel count in \"%s\": %d\n", str2, countVowels(str2))
40
41 str3 := "Rhythm"
42 fmt.Printf("Vowel count in \"%s\": %d\n", str3, countVowels(str3))
43
44 str4 := ""
45 fmt.Printf("Vowel count in \"%s\": %d\n", str4, countVowels(str4))
46}
Algorithm description viewbox

Count Vowels in String

Algorithm description:

This Go program counts the occurrences of vowels (a, e, i, o, u) within a given string, irrespective of their case. It utilizes a helper function to determine if a character is a vowel. This is a fundamental string manipulation task applicable in text analysis, natural language processing, and basic data validation.

Algorithm explanation:

The `countVowels` function iterates through each character of the input string `s`. For every character, it calls the `isVowel` helper function. The `isVowel` function checks if the character matches any of the lowercase or uppercase vowels using a `switch` statement. If `isVowel` returns `true`, a counter `vowelCount` is incremented. The loop continues until all characters are processed. The time complexity is O(n), where n is the length of the string, because each character is examined once. The space complexity is O(1) as only a few variables are used. An edge case for an empty string is handled, returning 0 vowels.

Pseudocode:

function countVowels(s):
  vowelCount = 0
  if length(s) == 0:
    return 0
  for each character char in s:
    if isVowel(char):
      vowelCount = vowelCount + 1
  return vowelCount

function isVowel(char):
  if char is 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
    return true
  else:
    return false