A vowel is a syllabic speech sound pronounced without any stricture in the vocal tract. The English alphabet has five vowels: A, E, I, O, U.
A String
is an object in Java that represents a sequence of characters. The Java String
class provides several methods to perform different operations.
To find the vowels in a given string, you need to compare every character in the given string with the vowel letters, which can be done through the charAt()
and length()
methods.
charAt()
: The charAt()
function in Java is used to read characters at a particular index number.length()
: The length()
function in Java is used to find the length of a string, i.e., the number of characters present in the string.The code snippets below show the syntax of the length()
and charAt
functions, respectively.
public int length();
public char charAt(int index)
The code below demonstrates how to find all the vowels in a string.
class Vowel { public static void main(String args[]) { String str = new String("Hi Welcome to my world!"); for(int i=0; i<str.length(); i++) { if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') System.out.println("Given string contains " + str.charAt(i)+" at the index " + i); } } }
The code above performs the following actions.
String
object is initialized.for
loop iterates through each character in the string, starting the iteration from i = 0
to i < str.length()
.i
is a vowel or not.i < str.length()
, i.e., until all the characters are processed.Through this process, the for
loop, charAt()
, and length()
functions can check for all the vowels present in a string in Java.
RELATED TAGS
CONTRIBUTOR
View all Courses