【发布时间】:2020-12-30 08:26:08
【问题描述】:
我试图在不使用数组split() 或StringBuilder 的情况下逐字反转字符串。到目前为止,这是我的代码。它有效,但我的输出不是我想要的。请参阅我的图像以获取输出。
我希望我的程序在新行上输出每个单词。还要注意窗帘上缺少字母“n”,最后两个单词之间没有空格。我该如何解决这个问题?
public static void main(String[] args) {
String sentence = new String("pay no attention to that man behind the curtain");
String reversed = "";
int endIndex = sentence.length()-1;
for(int i = endIndex; i >= 0; i--) {
if(sentence.charAt(i) == ' ') {
reversed += sentence.substring(i, endIndex);
endIndex = i;
}
}
reversed += sentence.substring(0, endIndex);
System.out.println(reversed);
}
【问题讨论】:
-
StringBuilder 有一个专门的方法。
-
调试您的程序以查看该字母丢失的位置。
标签: java string algorithm reverse