How to reverse a String in Java word by word

This example shows how to reverse a String word by word using java

Syntax:

public static String reverse(String input){
	StringBuilder sb = new StringBuilder();
	
	String tab[] = input.split( " " );
	String sep = "";
	for( int i = tab.length-1 ; i >= 0 ; i--){
	    sb.append( sep );	
	    sb.append( tab[i] );
	    
	    sep = " ";
	}
	
	return sb.toString();
}

Example:

The following code creates a method taking a String in input and returning a String. The input is split on the space character to separate the different words. The String is recreated looping on the array of words from the last element of the array to the first. Calling the reverse method twice returns the same String.

public class StringReverseWords {

    public static String reverse(String input){
	StringBuilder sb = new StringBuilder();
	
	String tab[] = input.split( " " );
	String sep = "";
	for( int i = tab.length-1 ; i >= 0 ; i--){
	    sb.append( sep );	
	    sb.append( tab[i] );
	    
	    sep = " ";
	}
	
	return sb.toString();
    }
    
    public static void main(String[] argv) {

	String test = "This is a test of the reverse method";

	// Call reverse 
	String output = reverse( test );
	
	System.out.println( test + " => " + output );
	
	// Same test calling reverse twice
	System.out.println( test + " => " + reverse( test ) + " => " + reverse(reverse( test )) );
    }

}

The output will be:

	
This is a test of the reverse method => method reverse the of test a is This
This is a test of the reverse method => method reverse the of test a is This => This is a test of the reverse method
	

References:

Java String

Recent Comments