Java Program to count all vowels in a string

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our string.

String str = "!Demo Text!";

To count vowels, loop through each every character and check for any of the vowel i.e.

if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
++vowelsCount;
}

The variable “vowelsCount” will give the count of all vowels.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "!Demo Text!";
      int vowelsCount = 0;
      for(char c : str.toCharArray()) {
         c = Character.toLowerCase(c);
         if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            ++vowelsCount;
         }
      }
      System.out.println("String "+str+" has "+ vowelsCount + " vowels.");
   }
}

Output

String !Demo Text! has 3 vowels.
raja
Published on 14-Dec-2018 06:44:49
Advertisements