Reversing a String by Character


String letters = "ABCDEF"; StringBuffer lettersBuff = new StringBuffer(letters); String lettersRev = lettersBuff.reverse().toString();



The StringBuffer class contains a reverse() method that returns a StringBuffer that contains the characters from the original StringBuffer reversed. A StringBuffer is easily converted into a String using the toString() method of the StringBuffer. So by temporarily making use of a StringBuffer, you are able to produce a second string with the characters of an original string in reverse order.

If you are using JDK 1.5, you can use the StringBuilder class instead of the StringBuffer class. The StringBuilder class has an API compatible with the StringBuffer class. The StringBuilder class will give you faster performance, but its methods are not synchronized; thus it is not thread-safe. In multithreaded situations, you should continue to use the StringBuffer class.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net