Ways to invert a string

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.