用Java反转给定的句子

时间:2010-04-26 13:14:03

标签: java string reverse

有谁能告诉我如何编写Java程序来反转给定的句子?

例如,如果输入为:

  

“这是一个面试问题”

输出必须是:

  

“问题采访是这个”

14 个答案:

答案 0 :(得分:24)

您将字符串按空格分割,然后向后迭代以组合反向句子。

String[] words =  "This is interview question".split(" ");

String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
   rev += words[i] + " ";
}

// rev = "question interview is This "

// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
   revb.append(words[i]);
   revb.append(" ");
}
// revb.toString() = "question interview is This "

答案 1 :(得分:23)

String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");

(使用来自commons-lang的ArrayUtilsStringUtils,但这些是简单的方法 - 只需几个循环)

答案 2 :(得分:19)

只是与众不同:一种递归的解决方案。不添加任何额外的空格。

public static String reverse(String s) {
   int k = s.indexOf(" ");
   return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}


System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"

我还会使用split改进\b解决方案(这很明显!)。

    String[] parts = "Word boundary is better than space".split("\\b");
    StringBuilder sb = new StringBuilder();
    for (int i = parts.length; i --> 0 ;) {
        sb.append(parts[i]);
    }
    System.out.println("[" + sb.toString() + "]");
    // prints "[space than better is boundary Word]"

答案 3 :(得分:6)

将它在空格字符上拆分为字符串数组,然后以相反的顺序遍历数组并构造输出字符串。

String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
    output += array[i];
    if (i != 0) { output += " "; }
}

答案 4 :(得分:6)

Bozho已经给出了一个很好的Java特定答案,但是如果没有Java API方法你需要解决这个问题:

要反转,你可以简单地将单个单词弹出到stack上,然后在没有单词的情况下将它们全部弹回。

(为了更清楚,Java确实提供了Stack class,因此也可以在Java中使用此方法。)

答案 5 :(得分:3)

每一个无聊的java:

List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
    b.append(s).append(' ');
}
b.toString().trim();

在groovy中它更具可读性:

"this is an interview question"
    .split("\\s")
    .reverse()
    .join(' ')

答案 6 :(得分:3)

我也尝试一下:这是一个使用堆栈和扫描仪的版本:

String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();

while(sc.hasNext()) {
    stack.push(sc.next());
}

StringBuilder output = new StringBuilder();

for(;;) { // forever
    output.append(stack.pop());

    if(stack.isEmpty()) {
        break; // end loop
    } else {
        output.append(" ");
    }
}

答案 7 :(得分:2)

public class ReverseString {

    public void reverse(String[] source) {

        String dest = "";
        for (int n = source.length - 1; n >= 0; n--) {
            dest += source[n] + " ";
        }
        System.out.println(dest);

    }

    public static void main(String args[]) {
        ReverseString rs = new ReverseString();
        String[] str = "What is going on".split(" ");
        rs.reverse(str);

    }

}

答案 8 :(得分:1)

更好的方法可能..已经看到了某个地方的逻辑......我的代码可以完成这项工作。

    public class revWords {

    public static void main(String[] args) {

        revWords obj = new revWords();
        String print = obj.reverseWords("I am God");
        System.out.println(print);

    }

    public String reverseWords(String words)
    {
      if(words == null || words.isEmpty() || !words.contains(" "))
        return words;

      String reversed = "";
      for( String word : words.split(" "))
        reversed = word + " " + reversed;

      return reversed;
    }

}

答案 9 :(得分:1)

  

我认为你不应该使用任何图书馆..   1)反转整个字符串   2)颠倒每个单词。

public static void revWord(char[] a) {

    // reverse whole
    revWord(a, 0, a.length);

    int st = -1;
    int end = -1;

    for (int i = 0; i < a.length; i++) {

        if (st == -1 && a[i] != ' ') {
            st = i;
        }
        if (end == -1 && a[i] == ' ' ) {
            end = i;
        }
        if(i == a.length-1){
            end=i+1;
        }

        if (st != -1 && end != -1) {
            revWord(a, st, end );

            st = -1;
            end = -1;
        }

    }

}

public static void revWord(char[] a, int s, int l) {
    int mid = (l - s) / 2;
    l--;

    for (int i = 0; i < mid; i++, l--) {
        char t = a[s+i];
        a[s+i] = a[l];
        a[l] = t;
    }
}

`

答案 10 :(得分:1)

还没有人提到过基于Java 8的基于Java 8的解决方案,它与Bozho's相同,但没有任何第三方库。所以这就是:

String input = "This is interview question";

List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));

答案 11 :(得分:1)

请尝试以下解决方案,这对我有用。

public class reverseline {

public static void main(String[] args) {
    // TODO Auto-generated method stub

        String str="This is interview question";
    String words[]=str.split(" ");
    for(int i=words.length-1;i>=0;i--){
        System.out.print(words[i]+" ");
    }
}

}

答案 12 :(得分:0)

StringTokenizer被宣布为遗产之前,许多人使用了 StringTokenizer 。以为我会把它留在这里。

String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence); 

while (tokens.hasMoreTokens()) { // Loop through each token
    reversed =  tokens.nextToken() + ' ' + reversed; //add to start
}

System.out.println(reversed.trim());

答案 13 :(得分:0)

最短的答案

public class ReverseSentance {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a sentance");
    String inputString = sc.nextLine();

    String[] words = inputString.split(" ");

    List<String> reverseWord = Arrays.asList(words);
    Collections.reverse(reverseWord);

    Iterator itr = reverseWord.iterator();

    while (itr.hasNext()) {
        System.out.print(itr.next() + " ");
    }
}

}

public class ReverseSentance {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a sentance");
    String inputString = sc.nextLine();

    String[] words = inputString.split(" ");

    for (int i = words.length-1 ; i >= 0; i--) {
        System.out.print(words[i] +" ");
    }
}