Search code examples
javasplitsentencetext-segmentation

Find vowels in each word from a sentence entered by the user (java)


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?


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.