How can I make a simple vowel counter method in Java?

11,352

Solution 1

char ch = word.charAt (i);
if (ch == 'a' || ch=='e') {

}

Solution 2

Using regular expressions you can try.

int count = word.replaceAll("[^aeiouAEIOU]","").length();

Solution 3

    String regex = "[aeiou]";               
    Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);   
    int vowelcount = 0;
    Matcher m = p.matcher(content);
    while (m.find()) {
      vowelcount++;
    }
    System.out.println("Total vowels: " + vowelcount);
Share:
11,352
Sergio Tapia
Author by

Sergio Tapia

I'm a 21 year old professional programmer that likes to read about a wide range of things related to programming. Currently, I'm pounding away at ASP.Net MVC2.

Updated on June 24, 2022

Comments

  • Sergio Tapia
    Sergio Tapia almost 2 years

    Here's my method:

    public char[] ReturnAllVowels(String word)
    {
        for (int i = 0; i < word.length(); i++)
        {
            if (word.contains("a" || "e" || "i" || "o" || "u"))     
            {
    
            }
        }        
    }
    

    It says that || cannot be applied to String class. How can I do this then?

  • Roman
    Roman over 14 years
    Hey, minusers, leave comments at least.