问题描述
我正在尝试不使用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);
}
解决方法
尝试以下代码:
Route
,
首先,有一个更好的方法来反转单词。但是让我们看看您的程序。
我希望我的程序在新行上输出每个单词。
如果要在新行中打印每个单词,可以将每个单词添加到单词列表中,然后在新行中打印每个单词,也可以在每个单词的末尾添加“ \ n”。
还要注意窗帘上的字母“ n”是如何丢失的,并且没有 最后两个词之间的空格。
这是因为Java中的endIndex
从sentence.length()-1
开始,而substring
的工作方式是从startIndex提取到endIndex-1,即endIndex是排他的,而startIndex是包含的。
您可以通过声明endIndex = sentence.length()
并从i = {sentence.length()-1
迭代到0
来解决它。
这样,代码将是:
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();
for(int i = sentence.length()-1; i >= 0; i--) {
if(sentence.charAt(i) == ' ') {
reversed += sentence.substring(i+1,endIndex) + "\n";
endIndex = i;
}
}
reversed += sentence.substring(0,endIndex);
System.out.println(reversed);
}
更好的方法是:
a)将您的字符串转换为字符数组
b)然后反转整个字符数组,该数组将变为:
niatruc eht dniheb nam taht ot noitnetta on yap
c)然后将每个空格之间的字母反转。
d)您将获得代表以下内容的新字符数组:
curtain the behind man that to attention no pay
您可以从新的字符数组构造一个字符串。