Logic - How to check if a character is a vowel in a given String?1 year ago

Let us say we are given a string and asked to print the vowels in the string. Vowels can be in upper case AEIOU or in lower case aeiou. Here instead of comparing all 10 values (5 in upper case and 5 in lower case), we convert the character to be compared to lower case and do the comparison. So we define a method isVowel to check if a given character is a vowel or not.

Let us explore the solutions in various programming languages.

Solution in C Programming Language:

#include<stdio.h>

int isVowel(char ch){
ch = tolower(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

int main()
{
char str[1001];
scanf("%s",str);
for(int index=0; str[index] != '\0'; index++){
if(isVowel(str[index])){
printf("%c",str[index]);
}
}
}

Solution in Java Programming Language:

import java.util.*;

public class Hello {

private static boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

public static void main(String... args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for (char ch : str.toCharArray()) {
if (isVowel(ch)) {
System.out.print(ch);
}
}

}

}

Solution in Python Programming Language:

def isVowel(ch):
ch = ch.lower()
return ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'

inputstr=input().strip();
for ch in inputstr:
if isVowel(ch):
print(ch, end='')

Solution in C++ Programming Language:

int isVowel(char ch)
{
ch = tolower(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

int main()
{
char str[1001];
cin >> str;
for(char *ptr = str; *ptr; ptr++)
{
if(isVowel(*ptr))
{
cout << *ptr;
}
}
return 0;
}