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