如何反转Java String的单词

时间:2013-04-09 18:47:10

标签: java string input

我试图让程序从扫描仪中获取字符串的输入,但是我想要分解输入的字符串并反转单词的顺序。这就是我到目前为止所拥有的。

Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
    // Will recognize a space in words
    if(Character.isWhitespace(welcome.charAt(i))) {
        Character a = welcome.charAt(i);
    }   
}

我想要做的是在它识别出空间,捕获它之前的所有内容,然后为每个空间,然后重新排列字符串。

7 个答案:

答案 0 :(得分:4)

问题后修改。

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

   public static void main( String[] args ) {
      final String welcome = "How should we get words in string form a List?";
      final List< String > words = Arrays.asList( welcome.split( "\\s" ));
      Collections.reverse( words );
      final String rev = words.stream().collect( Collectors.joining( ", " ));
      System.out.println( "Your sentence, reversed: " + rev );
   }
}

执行:

Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How

答案 1 :(得分:3)

我确实建议先扭转整个字符串。 然后反转两个空格之间的子串。

public class ReverseByWord {

    public static String reversePart (String in){
        // Reverses the complete string
        String reversed = "";
        for (int i=0; i<in.length(); i++){
            reversed=in.charAt(i)+reversed;
        }
        return reversed;
    }

    public static String reverseByWord (String in){
        // First reverses the complete string
        // "I am going there" becomes "ereht gniog ma I"
        // After that we just need to reverse each word.
        String reversed = reversePart(in);
        String word_reversal="";
        int last_space=-1;
        int j=0;
        while (j<in.length()){
            if (reversed.charAt(j)==' '){
                word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
                word_reversal=word_reversal+" ";
                last_space=j;
            }
            j++;
        }
        word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
        return word_reversal;
    }

    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println(reverseByWord("I am going there"));
    }
}

答案 2 :(得分:1)

以下是您在输入字符串中反转单词的方法:

Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();

if(!s.trim().contains(' ')) {
   return s;
}
else {

   StringBuilder reversedString = new StringBuilder();
   String[] sa = s.trim().split(' ');

   for(int i = sa.length() - 1; i >= 0: i - 1 ) {

      reversedString.append(sa[i]);
      reversedString.append(' ');
   }

   return reversedString.toString().trim();
}

希望这有帮助。

答案 3 :(得分:1)

如果你想减少代码行数,我想你可以查看我的代码:

package com.sujit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StatementReverse {
    public static void main(String[] args) throws IOException {
        String str;
        String arr[];
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a string:");
        str = br.readLine();
        arr = str.split("\\s+");

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

        }
    }
}

答案 4 :(得分:0)

public class StringReverse {
    public static void main(String[] args) {
        String str="This is anil thakur";
        String[] arr=str.split(" ");

        StringBuilder builder=new StringBuilder("");
        for(int i=arr.length-1; i>=0;i--){
            builder.append(arr[i]+" ");
        }
        System.out.println(builder.toString());
    }

}

Output: thakur anil is This 

答案 5 :(得分:0)

公共类ReverseWordTest {

public static String charRev(String str){

String revString =&#34;&#34;;

String [] wordSplit = str.split(&#34;&#34;);

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

String revWord =&#34;&#34;;

String s2 = wordSplit [i];

for(int j = s2.length() - 1; j&gt; = 0; j - ){

revWord = revWord + s2.charAt(j);  }

revString = revString + revWord +&#34; &#34 ;;

}

返回revString;

}

public static void main(String [] args){

System.out.println(&#34;输入你的字符串:&#34;);

扫描仪sc =新扫描仪(System.in);

String str = sc.nextLine();

的System.out.println(charRev(STR));

}

答案 6 :(得分:0)

    public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
    if(count==0||count==x.length) //that's for two edges.
      one=s+one;
    else
      one=s+" "+one;
    count++;
}
System.out.println(one); //reverse.
}