Tuesday, 3 January 2017

Write a Java Program to Count and Print Vowels and Consonants from String ?

Below Java program take string as input and it will prints all the vowels and consonants from String ,as well as it also prints total vowels and consonants count in string.

For Example : suppose "pushkar" is an input string and we can see that only two vowels are their i.e. "a" and "u" ,rest all the alphabets are consonants i.e. "p","s","h","k", and "r".
For detailed example please look the below program.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.ArrayList;
import java.util.List;

public class CountVowelsAndConsonants {
 
 public static void get(String str){
  char[] vowelsArr = {'a','e','i','o','u'};
  
  List<Character> vowels = new ArrayList<Character>();
  List<Character> consonants = new ArrayList<Character>();
  
  for(int i=0;i<str.length();i++){
   boolean status = false;
   for(int j=0;j<vowelsArr.length;j++){
    if(str.charAt(i) == vowelsArr[j]){
     status = true;
    }
   }
   if(status){
    vowels.add(str.charAt(i));
   }
   else{
    consonants.add(str.charAt(i));
   }
  }
  System.out.println("vowels : "+vowels);
  System.out.println("TOTAL VOWELS : "+vowels.size());
  System.out.println("\nconsonants : "+consonants);
  System.out.println("TOTAL CONSONANTS : "+consonants.size());
 }
 public static void main(String[] args) {
  CountVowelsAndConsonants.get("pushkar");
 }
}

Output :

vowels : [u, a]
TOTAL VOWELS : 2

consonants : [p, s, h, k, r]
TOTAL CONSONANTS : 5



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment