Question

I have a program that gives the following output:

Enter a Sentence: I am new to java

I

am

new

to

java

Number of vowels in: I am new to java = 6

My problem is that i need to get the vowels in each word of the sentence entered by the user.

For e.g. the output should be something like:

Enter a Sentence: I am new to java

I (1)

am (1)

new (1)

to (1)

java (2)

Number of vowels in: I am new to java = 6

I am using .split() to separate sentence entered and switch /.charAT statements for vowel checking.

Can someone please help me achieve this outcome?

Was it helpful?

Solution

The whole solution only needs a couple of lines of code:

for (String word : sentence.split(" +"))
    System.out.println(word + " (" + 
      word.replaceAll("[^aeiouAEIOU]", "")
      .length() + ")");

The way it works is the call to replaceAll() removes all non-vowels, so what remains is only vowels, then you simply take the length of that vowel-only String.

OTHER TIPS

I would suggest to build one String and loop through every char and check for a vowel.

String test = "I am new to Java";
int vowels = 0;

for (char c: test.toLowerCase().toCharArray()){
    if(c == 'a' || c =='e' || c=='i' || c=='o' || c=='u' ){
        vowels++;
    }
}
System.out.println(test + " Contains: " +vowels +" Vowels");
String n = "I am in Madurai";
int count = 0;
char c[] = new char[n.length()];
n.getChars(0, n.length, c, 0);

for(int i = 0; i < c.length; i++) {
    if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' || c[i] == 'u')
        count++;
}
System.out.println("Number of vowels in a given sentence: " + count);

Output:

Number of vowels in a given sentence: 7
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top