代码应该反转一个字符串所以如果我输入“你好,你怎么样”它应该返回“你是多么喜欢”,并且这些单词按照正确的顺序出现,但它们也出现了反转的字样(例如“ouy era woh ih”)有没有人看到我应该添加或取出的内容?
import java.util.*;
public class ReverseString
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse =reverse + original.charAt(i);
System.out.println("Reverse of entered string is "+reverse);
}
}
答案 0 :(得分:0)
您需要将字符串分解为如下字样:
splitArray = original.split("\\s+");
或者有更多细节:
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
String[] splitArray;
try {
splitArray = original.split("\\s+");
for (int i = splitArray.length - 1; i >= 0; i--) {
reverse = reverse + splitArray[i] + " ";
}
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Reverse of entered string is: " + reverse);
}
}
输出:
run:
Enter a string to reverse
this is a test
Reverse of entered string is: test a is this
答案 1 :(得分:0)
最简单的方法是以相反的顺序拆分和访问数组:
String str = "hi how are you";
String[] words = str.split(" ");
StringBuilder buffer = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
if(i != ( words.length - 1)) buffer.append(" ");
buffer.append(words[i]);
System.out.println(words[i]);
}
答案 2 :(得分:0)
在str
:
String [] parts = str.split (" ");
StringBuilder sb = new StringBuilder ();
for (int i = parts.length - 1; i >= 0; i--)
{
if (sb.length () > 0) sb.append (' ');
sb.append (parts [i]);
}
str = sb.toString ();