如何逐字反轉Java中的String

此示例顯示如何使用java逐字反轉String

句法:

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。 輸入在空格字符上分開以分隔不同的單詞。 重新構造String,從數組的最後一個元素到第一個元素的單詞數組循環。 調用反向方法兩次返回相同的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
	

參考文獻:

Java String

最近評論