1. Requirements
Reverses the string--enters a string, reverses it and outputs it.
For example: The input string is: Love. The output is: Evol.
Note: In the following paragraphs, string flipping is also the meaning of reverse order.
2. Ideas
There are two great ways to think about it:
(1) StringBuffer provides a string rollover function, directly using the API.
(2) The string essence is a char array that is used to reverse the strings.
3. Code
1 PackageCom.myeclipse;2 3 /**4 * Reverse String--Enter a string, reverse it and output5 * @authorMrchen6 *7 */8 Public classStringreverse {9 Ten /** One * @paramargs A */ - Public Static voidMain (string[] args) { - //TODO auto-generated Method Stub theString str = "Love"; - //System.out.println ("Reversebystringbuffer Result:" +reversebystringbuffer (str)); - System.out.println (Reversebychararray (str)); - } + - /** + * Using string essence is a char array to flip a string A * @paramStr at * @return - */ - Public Staticstring Reversebychararray (String str) { - Char[] Array =New Char[Str.length ()]; -Str.getchars (0, Str.length (), array, 0); - //piling, viewing char array contents in //System.out.println (array.length); - //For (char c:array) { to //System.out.println (c); + // } - //creates a new target array to hold the string after the rollover the Char[] Dest =New Char[Array.Length]; * //Flip Character $ for(inti=0; i<dest.length; i++ ) {Panax NotoginsengDest[i] = array[array.length-1-i]; - } the return NewString (dest); + } A the + /** - * Using the string inversion method provided by StringBuffer $ * @paramStr $ * @return - */ - Public Staticstring Reversebystringbuffer (String str) { theStringBuffer SB =NewStringBuffer (str); -StringBuffer sb_out =sb.reverse ();Wuyi returnsb_out.tostring (); the } - Wu -}
Implementing String Flipping4. Summary
(1) Reverse string is a very simple function, but there are two thinking direction: One is to think on the string (you can think that StringBuffer is wrapped in string type, from the StringBuffer construction method can be verified), One is to think under string (the nature of string, deep thinking).
(2) Converting a string to char[] can also be done without a ready-made API, such as using a For loop, to get each character of the string one by one by increasing the index value.
(3) char[] Flip also have other ways, such as the simplest a=b,b=c,c=a this transfer value exchange.
(4) If you know the C language, you can even manipulate it directly with a pointer.
Text Item Series [1]--reverse string