Java implementation string inversion

Source: Internet
Author: User

Summarize a common programming topic for Java Interviewing: Reverse the ' abc123 ' string and write down the methods you can think of.

1. Using the reverse member method of StringBuffer or StringBuilder:

  // StringBuffer   Public Static string Reverse1 (String str) {    returnnew  StringBuilder (str). reverse (). ToString ( );  }

2. Use the ToCharArray method of string to first convert the string to a char type array and then re-stitch the individual characters:

  // ToCharArray   Public Static string Reverse2 (String str) {    char[] chars = Str.tochararray ();     = "";      for (int i = chars.length-1; I >= 0; i--) {      + = chars[i]    ;    } return reverse;  }

3. Use the CharAt method of string to remove individual characters from the string:

  // charAt   Public Static string Reverse3 (String str) {    = "";     int length = str.length ();      for (int i = 0; i < length; i++) {      = Str.charat (i) + reverse;    }     return reverse;  }

Finally, add the test code in the Main method:

   Public Static void Main (string[] args) {    = "abc123";    System.out.println ("----------------");      for (int i = s.length ()-1; I >= 0; i--) {      System.out.print (S.charat (i));    }    System.out.println ("----------------");    System.out.println ("before transformation:" + s);    System.out.println ("after transform:" + Reverse1 (s));    System.out.println ("after transform:" + Reverse2 (s));    System.out.println ("after transform:" + Reverse3 (s));  }

Java implementation string inversion

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.