この例では、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();
}
次のコードは、Stringを入力に取り、Stringを返すメソッドを作成します。 入力はスペース文字で分割され、異なる単語を区切ります。 文字列は、配列の最後の要素から最初の要素までの単語の配列のループを再作成します。 reverseメソッドを2回呼び出すと、同じ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