drJava drJava - 6 months ago 28
Java Question

Count vowels in a word

I need to find count of the vowels in a word. However, when I compare the letters in the word whether they are vowel or not,

For example, what I do like the one below,

if( word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'u'
...... ) //the rest is omitted

the if statement gets too long. Is there a way to compare them with a regex or regex-like comparison and give me the number of occurrences?

Answer

If you want to find all vowels

String line = "Ahis order was placed for QT3000! OK?";
String pattern = "(?i)[aeiou]";

Pattern r = Pattern.compile(pattern);

Matcher m = r.matcher(line);

while (m.find()) {
   System.out.println(m.group(0) );
}

If you want to find number of times they occur you can use replace like

String line = "Ahis order was placed for QT3000! OK?";
String pattern = "(?i)[aeiou]";
System.out.println(line.replaceAll(pattern, "").length());

NOTE :- (?i) is inline modifier which indicates whatever pattern follows it will be case insensitive

Comments