In the other examples on this website you might have seen how to reverse a string using StringBuffer
, StringUtils
from Apache Commons Lang 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.util;
import java.util.Stack;
import java.util.StringTokenizer;
public class ReverseStringByWord {
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<String> stack = new Stack<>();
while (st.hasMoreTokens()) {
stack.push(st.nextToken());
}
// Print each word in reverse order
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024