我是 Java 新手,我为 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;
}
}
我可以做出任何改进吗?
最新的 Java 版本中是否有我可能不知道的巧妙 Java 技巧?我有 C# 背景。
谢谢!
最佳答案
我将重写 isVowel(char ch)
如下:
return "aeiou".indexOf(ch) != -1;
我会写以下内容:
// String first = word.substring(position, word.length());
String first = word.substring(position);
我还会重命名方法名称以遵循编码约定。
当然,对于我来说,我也会使用正则表达式来代替 substring
和 for
循环。
System.out.println("string".replaceAll("([^aeiou]+)(.*)", "$2$1ay"));
// ingstray
引用文献
关于java - 我可以改进这个 Pig-Latin 转换器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3399548/