查找单词中第一个元音出现的位置

Jac*_*ong 3 java arrays sorting string

我正在尝试编写一个将英语翻译成 PigLatin 的程序。我目前正在尝试解决在哪里找到单词的第一个元音的部分,这样程序就可以正确地分割单词并正确地重新排列它。

例如,字符串“hello I am a Guy”变为“ellohay Iyay amyay aayy uygay”。(在列表中,我认为我的猪拉丁语是正确的,这与我创建的示例不同。

因此,“what”这个词就变成了“atwhay”。程序发现第一个元音位于槽 2,然后给出整数 2。

我想首先将它与一个字符串进行比较,元音=“aeiouy”,然后从那里开始,但我被困住了。这是我所拥有的:

public static int indexOfFirstVowel(String word){
   int index=0;
   String vowels="aeiouy";
   return index;

}
Run Code Online (Sandbox Code Playgroud)

理论上索引将更新到第一个元音所在的位置。

fur*_*kle 5

这是您可以做到的一种方法:

final static String vowels = "aeiouy";
public static int indexOfFirstVowel(String word){
    String loweredWord = word.toLowerCase();

    for (int index = 0; index < loweredWord.length(); index++)
    {
        if (vowels.contains(String.valueOf(loweredWord.charAt(index))))
        {
            return index;
        }
    }

    // handle cases where a vowel is not found
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

这只是逐个字符地遍历单词,并检查每个字符以查看它是否存在于元音字符串中。