如何在给定的字符串中找到元音?

时间:2015-03-03 04:29:28

标签: java

我正在努力做一个简单的代码。

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

我尝试使用此代码检查单词是否没有元音,如果是,则添加“ay”。到目前为止没有运气。我认为我的问题是在indexOf方法的某个地方,有人可以向我解释一下吗?

2 个答案:

答案 0 :(得分:2)

这样的事情:

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
}

答案 1 :(得分:0)

您可以使用正则表达式和String.matches(String regex)。首先是正则表达式。 [AEIOUaeiou]vowel character class.*(s)将使用任意可选的非元音。

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

然后你可以测试你的word喜欢

if (word.matches(regex)) {

注意您的vowels已经是小写的(此处不需要小写word,正则表达式包含大写)。

相关问题