In this example we use the java.text.CharacterIterator
implementation class java.text.StringCharacterIterator
to reverse a string. It’s done by reading a string from the last index up to the beginning of the string.
package org.kodejava.text;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class StringCharacterIteratorReverseExample {
private static final String text = "Jackdaws love my big sphinx of quartz";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
System.out.println("Before = " + text);
System.out.print("After = ");
// Iterates a string from the last index to the beginning.
for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it.previous()) {
System.out.print(ch);
}
}
}
The result of the code snippet above:
Before = Jackdaws love my big sphinx of quartz
After = ztrauq fo xnihps gib ym evol swadkcaJ
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