我可以改进这个 Pig-Latin 转换器吗?

问题描述:

我是 Java 的新手,我为 PigLatin 制作了这个小翻译器.

I'm brand-spanking new to Java and I made this little translator for PigLatin.

package stringmanipulation;

public class PigLatinConverter {
    public String Convert(String word){
        int position = 0;
        if (!IsVowel(word.charAt(0))) {
            for (int i= 0; i < word.length(); i++) {
                if (IsVowel(word.charAt(i))) {
                    position = i;
                    break;
                }
            }
            String first = word.substring(position, word.length());
            String second = word.substring(0, position) + "ay";

            return first + second;
        } else {
            return word + "way";
        }
    }

    public boolean IsVowel(char c){
        if (c == 'a')
            return true;
        else if(c == 'e')
            return true;
        else if(c == 'i')
            return true;
        else if(c == 'o')
            return true;
        else if(c == 'u')
            return true;
        else
            return false;        
    }
}

我有什么可以改进的吗?

Are there any improvements I can make?

在最新的 Java 版本中是否有任何我可能不知道的漂亮的 Java 技巧?我来自 C# 背景.

Are there any nifty Java tricks that are in the newest Java version I might not be aware of? I come from a C# background.

谢谢!

我将 isVowel(char ch) 改写如下:

return "aeiou".indexOf(ch) != -1;

我会改写以下内容:

// String first = word.substring(position, word.length());
   String first = word.substring(position);

我还会重命名方法名称以遵循编码约定.

I'd also rename method names to follow coding convention.

当然,作为我,我也会使用正则表达式而不是 substringfor 循环.

And of course, being me, I'd also use regex instead of substring and for loop.

System.out.println("string".replaceAll("([^aeiou]+)(.*)", "$2$1ay"));
// ingstray

参考资料