![](/img/trans.png)
[英]java: reverse word using StringBuffer without using String.split
[英]How can I reverse a string word by word without using arrays, split() or StringBuilder
我试图在不使用数组、 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);
}
试试这个代码:
import java.util.Scanner;
public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");
Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
System.out.println("Reversed string is:");
System.out.println(reverse);
}
}
首先,有一个更好的方法来反转单词。 但是让我们看看你的程序。
我希望我的程序在新行上输出每个单词。
如果您想在新行中打印每个单词,您可以将每个单词添加到单词列表中并在新行中打印每个单词,或者您可以在每个单词的末尾添加“\\n”。
还要注意窗帘中的字母“n”是如何丢失的,并且最后两个单词之间没有空格。
这是因为endIndex
开始于sentence.length()-1
并且 Java 中的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
并且您可以从新的字符数组构造一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.