简体   繁体   中英

How to reverse words of a Java String

Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.

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);
    }   
}

What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.

Edit after questions.

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 );
   }
}

Execution:

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

I did suggest first reverse the whole string. Then reverse the substring between two spaces.

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"));
    }
}

Here is the way you can reversed the word in entered string:

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();
}

Hope this helps.

If you wanted to reduce the number of line of code, I think you can look into my code :

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;
            }

        }
    }
}
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 
public class ReverseWordTest {

  public static String charRev(String str) {

    String revString = "";
    String[] wordSplit = str.split(" ");

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

      String revWord = "";
      String s2 = wordSplit[i];

      for (int j = s2.length() - 1; j >= 0; j--) {
        revWord = revWord + s2.charAt(j);
      }

      revString = revString + revWord + " ";
    }
    return revString;
  }

  public static void main(String[] args) {
    System.out.println("Enter Your String: ");
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    System.out.println(charRev(str));
  }
    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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM