Jack Nguyen
Jack Nguyen

Reputation: 103

How to find vowels in a given string?

Just a simple code I'm trying to do.

String vowels = "aeiou";
if ( word.indexOf(vowels.toLowerCase()) == -1 ){
        return word+"ay";
}

I've tried using this code for checking if a word has no vowels and if so adds "ay" to it. So far no luck. I think my problem is somewhere around the indexOf method, can anyone explain it a bit more to me?

Upvotes: 2

Views: 761

Answers (2)

DnR
DnR

Reputation: 3507

Something like this:

public String ModifyWord(String word){
    String[] vowels = {"a","e","i","o","u"};
    for (String v : vowels) {
        if(word.indexOf(v) > -1){ // >-1 means the vowel is exist
           return word;
        }
    }
    return word+"ay"; //this line is executed only if vowel is not found
}

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could use a regular expression, and String.matches(String regex). First, a regular expression. The [AEIOUaeiou] is a vowel character class and the .*(s) are to consume any optional non-vowel(s).

String regex = ".*[AEIOUaeiou].*";

Then you can test your word like

if (word.matches(regex)) {

Note your vowels are already lowercase (no need to lowercase word here, the regular expression includes uppercase).

Upvotes: 0

Related Questions