Friday, December 14, 2018

Golang Example - Check alphabet is Vowel or consonant

In this example, We will learn below programs. how to check alphabet is vowel or consonant using if-else and switch case examples and Count of vowels in a String.
the vowel is called for a character if Character contains any of a, e, i, o, u characters

Please have a look of below golang features before understanding this programs

Example program to check alphabet is Vowel or consonant using if else statement

package main

import (
 "fmt"
)

func isVowel(character rune) {
 if character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u' {
  fmt.Printf(" %c is vowel\n", character)
 } else {
  fmt.Printf(" %c is consonant\n", character)
 }

}
func main() {
 isVowel('a') // vowel
 isVowel('b') // consonant
}
Output is
a is vowel
b is consonant
In the above example, Character is stored as rune type. to check variable character to vowel or consonant, if character contains any one (a,e,i,o,u) using if else statement.

Example program to check alphabet is Vowel or consonant using a switch case

package main

import (
 "fmt"
)

func isVowel(character rune) {
 switch character {
 case 'a', 'e', 'i', 'o', 'u':
  fmt.Printf(" %c is vowel\n", character)
 default:
  fmt.Printf(" %c is consonant\n", character)
 }
}
func main() {
 isVowel('e') // vowel
 isVowel('g') // consonant
}
Output is
e is vowel
g is consonant
Instead of an if-else statement, Switch case is used. if the character is matched with any of characters (a,e,i,o,u), the case is printed with a vowel to console. default case consonant is printed to console

Example Calculate for vowels count in a String

package main

import (
 "fmt"
)

func main() {
 str := "kiran"
 count := 0
 for _, ch := range str {
  switch ch {
  case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
   count++
  }
 }
 fmt.Printf(" %s string contains vowels count: %d\n", str, count)

}
Output is
kiran string contains vowels count: 2

Related article


EmoticonEmoticon