英文:
Reverse a sentence using StringBuilder
问题
public String reverseWords(String s) {
int i = s.length() - 1;
StringBuilder resultBuilder = new StringBuilder();
while (i >= 0) {
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
if (i < 0) {
break;
}
int j = i;
while (j >= 0 && s.charAt(j) != ' ') {
j--;
}
String word = s.substring(j + 1, i + 1);
resultBuilder.append(word).append(' ');
i = j;
}
return resultBuilder.toString().trim();
}
英文:
The below code I used string as result and just reverse sentence for example input: " the sky is blue " and I get output:"blue is sky the". How I can use SpringBuilder instead String and then how I can reverse sentence and also words? example input: " the sky is blue " and I want this output "eulb is yks eht"
Please help me to modify the below code.
public String reverseWords(String s) {
int i = 0;
int j = 0;
String result = "";
while(s.length()>i){
while(s.length()>i && s.charAt(i)==' '){
i++;
}
if(i>=s.length()) break;
j = i;
while(s.length()>j && s.charAt(j)!=' '){
j++;
}
String word = s.substring(i,j);
result = word+" "+result;
i = j;
}
return result.trim();
}
答案1
得分: 0
你可以按以下方式使用StringBuilder
:
String str = " the sky is blue ";
str = str.replaceAll("\\s+", " ");
StringBuilder sb = new StringBuilder(str.trim());
System.out.println(sb.reverse().toString());
输出结果:
eulb si yks eht
英文:
You can use StringBuilder
as follows:
String str = " the sky is blue ";
str = str.replaceAll("\\s+", " ");
StringBuilder sb = new StringBuilder(str.trim());
System.out.println(sb.reverse().toString());
Output:
eulb si yks eht
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论