How do I reverse a string by word?
Category: java.lang, viewed: 1370 time(s).
On the previous example in this website you might have seen how to reverse a string using StringBuffer, StringUtils from Apache commons library or using the CharacterIterator.
In this example you'll see another way that you can use to reverse a string by word. Here we use the StringTokenizer and the Stack class.
package org.kodejava.example.lang; import java.util.Stack; import java.util.StringTokenizer; public class ReverseByWord { public static void main(String[] args) { // // The string that we'll reverse // String text = "Jackdaws love my big sphinx of quartz"; // // We use StringTokenize to get each word of the string. You might try // to use the String.split() method if you want. // StringTokenizer st = new StringTokenizer(text, " "); // // To reverse it we can use the Stack class, which implements the LIFO // (last-in-first-out). // Stack stack = new Stack(); while (st.hasMoreTokens()) { stack.push(st.nextToken()); } // // Print each word in reverse order // while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); } } } |
Related Examples
- How do I read system property as an integer?
- How do I decode string to integer?
- How do I insert a string in the StringBuilder?
- How do I remove substring from StringBuilder?
- How do I convert varargs to an array?
- How do I remove trailing white space from a string?
- How do I remove leading white space from a string?
- How do I create a method that accept varargs in Java?
- How do I know a class of an object?
- How do I replace characters in string?
|
|