Write a java program to find vowels in a string?
Write a java program to find vowels in a string?
Write a java program to find vowels in a string. Write some testcases to test your program output. Sample output and TestCase:
Sample input to the program
String s = TestingDocs
Sample output of the program:
Input String: TestingDocs
First vowel: e at position 2.
Last vowel: o at position 9.
Java Program
package com.javaautomation.questions;
import java.util.Scanner;
public class VowelStringLocator {
/* This method returns true if c is an upper case or lower case vowel
* or false otherwise. Vowels in English alphabets aeiouAEIOU*/
public static boolean isVowel(char c) {
/* Checking for both upper case and lower case vowels */
/* || logical or */
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U')
return true;
else
return false;
}
/* This method returns the position of the first vowel in s or -1
* if s contains no vowels at all. */
public static int positionOfFirstVowel(String s) {
char c;
/* in a loop check for each character in s for a vowel */
/* if vowel return the index and stop */
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (isVowel(c))
return i + 1;
}
return -1;
}
/* returns the position of the last occurrence of a vowel in
* s or -1 if s contains no vowels at all. It is just the same as above
* method just that we check the string from reverse */
public static int positionOfLastVowel(String s) {
char c;
/* in a loop check for each character in s for vowel */
/* if vowel return the index and stop */
for (int i = s.length() -1 ; i >= 0; i--) {
c = s.charAt(i);
if (isVowel(c))
return i + 1;
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String s;
System.out.println("Please enter Input String");
s = input.next();
System.out.println("Input String is:" + s);
int position = positionOfFirstVowel(s);
if(position != -1)
{
System.out.println("First vowel:" + s.charAt(position-1) + " at position " + position);
}
else {
System.out.println("First vowel:NOT FOUND");
}
position = positionOfLastVowel(s);
if(position != -1)
{
System.out.println("Last vowel:" + s.charAt(position-1) + " at position " + position);
}
else {
System.out.println("Last vowel:NOT FOUND");
}
input.close();
}
}
Output of the program.
Please enter Input String
TestingDocs
Input String is:TestingDocs
First vowel:e at position 2
Last vowel:o at position 9

Test case
Please enter Input String
123456789
Input String is:123456789
First vowel:NOT FOUND
Last vowel:NOT FOUND
Test case
Please enter Input String
Apple a day keeps doctor away!
Input String is:Apple
First vowel:A at position 1
Last vowel:e at position 5