我有以下代码可以逐词反转字符串,但是我有一个问题,首先,有人能指出如何改进代码吗?其次,我该怎么去掉新字符串开头的空格。
String str = "hello brave new world";
tStr.reverseWordByWord(str)
public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";
for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}
return reverse;
}
目前这个词组变成了:
olleh evarb wen dlrow
请注意新字符串开头的空格。
if((str.charAt(i) == ' ') || (i == strLeng)){ if(i==strLeng){ temp+=" "; } for(int j = temp.length()-2; j >= 0; j--){
但如果你正在寻找更好的编码方式,Dawood已经提供了最简单和内置的方法。 - prajeesh kumar