问题原文链接:
问题思路很简单,就是使用StringBuilder words变量存储每个单词。至于单词的后缀“a”也是使用变量去储存,遇到空格增加一个“a”。代码如下:
public String toGoatLatin(String S) {
StringBuilder sentence = new StringBuilder();//返回的句子
StringBuilder words = new StringBuilder();//单词储存器
String postfix = "";//每个单词的后缀,遇到空格就+a
//对字符串进行遍历,遇到空格就把上一个单词添加到sentence,不要忘记添加空格
for (int i = 0;i<S.length();i++){
if (S.charAt(i) != ' '&& i != S.length()-1){
words.append(S.charAt(i));
continue; }
if (i == S.length()-1)
words.append(S.charAt(i));
postfix+="a";
int length = words.length();
//对单词首字符进行判断
if (words.charAt(0) == 'a'||words.charAt(0) == 'e'|| words.charAt(0) == 'i' ||
words.charAt(0) == 'o'||words.charAt(0) == 'u'||words.charAt(0) == 'A'||words.charAt(0) == 'E'|| words.charAt(0) == 'I' ||
words.charAt(0) == 'O'||words.charAt(0) == 'U'){
words.append("ma").append(postfix);
sentence.append(words).append(" ");
words = new StringBuilder();//对单词储存器进行清空,以便下一个单词使用
}else{
words.append(words.charAt(0)).append("ma").append(postfix);
words.deleteCharAt(0);
/*
*不使用库函数
* StringBuilder tmp="";
*for(int i = 1;i<words.length();i++){
* tmp.append(words.charat(i));}
* */
sentence.append(words).append(" ");
words = new StringBuilder();
}
}
return sentence.toString().substring(0,sentence.length()-1);
/*
* 不使用库函数,同理上述
* */
}