Este exemplo mostra como inverter uma palavra String por palavra usando java
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();
}
O código a seguir cria um método que recebe uma string na entrada e retorna uma string. A entrada é dividida no caractere de espaço para separar as diferentes palavras. O String é recriado em loop no array de palavras do último elemento do array para o primeiro. Chamar o método reverso duas vezes retorna a mesma 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 )) );
}
}
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