Java program to count the number of vowels in a String

Calculate no of vowel in a String

In this program we’re going to check how many vowels are present in a given String . There are five vowels in English vocabulary, they are – ‘a’, ‘e’, ‘i’, ‘o’, ‘u’.

A String is entered in this case is “s” variable So, we need to check how many vowels are present in given string

  • Either we use two if conditions, one for checking lower case and one for checking uppercase, or
  • We convert the entire string into uppercase or lowercase, and then count the number of vowels.

For Example, in the string prepinsta then in that case then vowesl are 3 (a,e,i)

Java Program to calculate no of vowels in a string

Algorithm

  • Take a String input from user store in variable called “s” 
  • Convert String to char array using toCharArray() 
  • Start for loop from i=0 to i<s.length()
  • Check condition if s.charAt(i)==’a’ or s.charAt(i)==’e’ or s.charAt(i)==’i’ or s.charAt(i)==’o’ or s.charAt(i)==’o’ to increment vowel++
  • Take else if part s.charAt(i)>=’a’ && s.charAt(i)<=’z’ to increment consonant ++
  • Take another else if part s.charAt(i)>=’1′ && s.charAt(i)<=’9′ to increment digit++
  • Take another else if part s.charAt(i)==’ ‘ to increment whitespaces++
  • Take else part to increment symbols++

Code in Java

import java.util.Scanner;

public class CountTheNumberOfVowels {

	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		System.out.println("Enter String");
		String s = sc.nextLine();
		char[] c = s.toCharArray();
		int vowel=0;
		
		for (int i = 0; i < s.length(); i++) { 
                    if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='o') 
                       vowel++; 
		}
  
	System.out.println("Vowels: " + vowel);

}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter String : prepinsta
Vowels: 3

One comment on “Java program to count the number of vowels in a String”