Packagecom.itheima_07;ImportJava.util.Scanner;/** String Inversion * Example: keyboard input "ABC" * Output: "CBA" * * Analysis: * A: Keyboard input a String * B: Write method to implement string inversion * A: the word The string is traversed backwards, and each of the resulting characters is spliced into strings. * B: Convert the string to a character array, then invert the character array, and finally convert the character array to a string * C: Call method * D: Output result*/ Public classStringTest2 { Public Static voidMain (string[] args) {//keyboard Input A stringScanner sc =NewScanner (system.in); System.out.println ("Please enter a string:"); String s=Sc.nextline (); //Write method to implement string inversion//Calling MethodsString result =reverse (s); //Output ResultsSYSTEM.OUT.PRINTLN ("Result:" +result); } /** The string is traversed backwards, and each of the resulting characters is spliced into a string. * Two explicit: * Return value type: String * parameter list: string s*/ /*Public static string reverse (string s) {string ss = ""; for (int x=s.length ()-1; x>=0; x--) {ss + = S.charat (x); } return SS; } */ //converts a string to a character array, then reverses the character array, and finally converts the character array to a string Public Staticstring Reverse (string s) {//Convert a string to a character array Char[] CHS =S.tochararray (); //invert a character array for(intStart=0,end=chs.length-1; start<=end; start++,end--) { Chartemp =Chs[start]; Chs[start]=Chs[end]; Chs[end]=temp; } //Finally, the character array is converted to a stringString SS =NewString (CHS); returnSS; }}
Ways to invert a string