如何在字符串中找到第一个元音的索引? [英] how to find index of first vowel in a string?

查看:138
本文介绍了如何在字符串中找到第一个元音的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这部分我想实现,但不知道如何:
在Pig Latin中,所有辅音直到第一个元音应该移动到单词的结尾。所以当laptop仍然是aptoplay,string应该成为ingStray。

This part i want implemented but don't know how: In Pig Latin, all the consonants until the first vowel should be moved to the end of the word. So while "laptop" will still be "aptoplay", "string" should become "ingStray".

我有这个,第一部分工作很好。 >

I have this, the first part works just fine.

public static String doStuff(String word) {
    int number = 0;
    char[] vowel = { 'a', 'e', 'i', 'o', 'u' };
    char first = word.charAt(0);
    char second = Character.toLowerCase(first);
    if (second == 'a' || second == 'e' || second == 'i' || 
            second == 'o' || second == 'u') {
        word = word + "ay";
    } else {
        for (int i = 0; i < word.length(); i++) {
        for (int j = 0; j < 5; j++) {
            if (word.charAt(i) == vowel[j]) {
                word = word.substring(i + 1) + word.substring(i) + "ay";
                break;
            }
        }
    }
    return word;
}


推荐答案

code> break 应该突破两个循环。要这样做,在你的第一个循环之前放置一个标志

First of all, your break should break out of both loops. To do so, put a flag before your first loop like

outerloop:
for (int i = 0; i < word.length(); i++) {

; put break outerloop;

其次,

word = word.substring(i + 1) + word.substring(i) + "ay";

不工作,因为当您找到元音时, i + 1 应该只是 i 。然后,ay之前的子字符串的其余部分应该是开头的辅音,因此 0,i 而不是只是 i 。总之,这提供了

doesn't work, because when you find the vowel, you want to keep it in front, so i + 1 should be just i. Then, the rest of the substring before "ay" should be the consonants at the beginning, so 0, i instead of just i. In all, this gives

outerloop:
    for (int i = 0; i < word.length(); i++) {
        for (int j = 0; j < 5; j++) {
            if (word.charAt(i) == vowel[j]) {
                word = word.substring(i) + word.substring(0, i) + "ay";
                break outerloop;
            }
        }
    }

这篇关于如何在字符串中找到第一个元音的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆