0

该代码应该反转一个字符串,所以如果我输入“你好吗”它应该返回“你是多么嗨”并且单词以正确的顺序出现,但它们的单词也颠倒了(例如“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);
        }
    }
4

3 回答 3

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 
于 2013-02-08T20:20:46.717 回答
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]);
}
于 2013-02-08T20:22:31.007 回答
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 ();    
于 2013-02-08T20:22:58.980 回答