Java Reference
In-Depth Information
See Also
The Unicode program in this topic's online source displays any 256-character section of the
Unicode character set. You can download documentation listing every character in the
Unicode character set from the Unicode Consortium .
Reversing a String by Word or by Character
Problem
You wish to reverse a string, a character, or a word at a time.
Solution
You can reverse a string by character easily, using a StringBuilder . There are several ways
to reverse a string a word at a time. One natural way is to use a StringTokenizer and a
stack. Stack is a class (defined in java.util ; see Stack ) that implements an easy-to-use
last-in, first-out (LIFO) stack of objects.
Discussion
To reverse the characters in a string, use the StringBuilder reverse() method:
StringRevChar.java
String sh = "FCGDAEB" ;
System . out . println ( sh + " -> " + new
new StringBuilder ( sh ). reverse ( ));
The letters in this example list the order of the sharps in the key signatures of Western music;
in reverse, it lists the order of flats. Alternatively, of course, you could reverse the characters
yourself, using character-at-a-time mode (see Processing a String One Character at a Time ).
A popular mnemonic, or memory aid, for the order of sharps and flats consists of one word
for each sharp instead of just one letter, so we need to reverse this one word at a time.
Example 3-6 adds each one to a Stack (see Stack ) , then processes the whole lot in LIFO or-
der, which reverses the order.
Example 3-6. StringReverse.java
Search WWH ::




Custom Search