我可以改进这个 Pig-Latin 转换器吗? [英] Can I improve this Pig-Latin converter?

查看:31
本文介绍了我可以改进这个 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

参考资料

  • Java 编码约定 - 命名约定
  • 这篇关于我可以改进这个 Pig-Latin 转换器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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