Iterate over a string backward in Java
This post will discuss various methods to iterate over a string backward in Java.
1. For loop
We can use a simple for-loop to process each character of the string in the reverse direction. This approach is very effective for strings having fewer characters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Main { // Iterate over a string backward public static void main(String[] args) { String s = "Reverse String"; // using simple for-loop for (int i = s.length() - 1; i >= 0; i--) { System.out.print(s.charAt(i)); } } } |
2. Convert to character array
In this approach, we initially reverse the string. Then we convert the reversed string to a character array by using the String.toCharArray() method. Finally, we iterate the char[] using a for-each loop, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { // Iterate over a string backward public static void main(String[] args) { String s = "Reverse String"; // reverse the string and convert it to `char[]` array char[] chars = new StringBuilder(s).reverse().toString() .toCharArray(); // iterate over char[] using the for-each loop for (char ch: chars) { System.out.print(ch); } } } |
3. Using CharacterIterator
We can also use the CharacterIterator interface that provides bidirectional iteration for a String.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.text.CharacterIterator; import java.text.StringCharacterIterator; class Main { // Traverse the string backward, from end to start public static void traverseBackwards(CharacterIterator itr) { char ch = itr.last(); while (ch != CharacterIterator.DONE) { System.out.print(ch); ch = itr.previous(); } } // Iterate over a string backward public static void main(String[] args) { String s = "Reverse String"; CharacterIterator it = new StringCharacterIterator(s); traverseBackwards(it); } } |
4. Using String.Split() method
String.split() splits the specified string and returns an array of strings created by splitting this string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Main { // Iterate over a string backward public static void main(String[] args) { String s = "Reverse String"; String[] arr = s.split(""); for (int i = arr.length - 1; i >= 0; i--) { System.out.print(arr[i]); } } } |
5. Using Guava Library
Guava’s Lists.charactersOf() returns a view (not a copy) of the specified string as an immutable list of characters. After getting a view, we can process it using an iterator.
The List interface provides a special iterator, called a ListIterator that allows bidirectional access. We can call the List.listIterator(index) method to get a ListIterator over the list elements starting from the specified position in the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import com.google.common.collect.Lists; import java.util.ListIterator; class Main { // Iterate over a string backward public static void main(String[] args) { String s = "Reverse String"; // use `ListIterator` to iterate list in reverse order ListIterator<Character> itr = Lists.charactersOf(s) .listIterator(s.length()); // hasPrevious() returns true if the list has a previous element while (itr.hasPrevious()) { System.out.print(itr.previous()); } } } |
6. Using Reflection
For longer strings, we can inspect any string using reflection and access the backing array of the string. To find the name of the backing array, we can print all the fields of String class using the following code and search one with the type char[].
|
1 2 3 4 5 6 7 8 9 |
Field[] fields = String.class.getDeclaredFields(); Arrays.asList(fields) .stream() .filter(x -> x.toString().contains("char[]")) .forEach(x -> { int index = x.toString().lastIndexOf(".") + 1; System.out.print(x.toString().substring(index)); // prints "value" }); |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.lang.reflect.Field; class Main { // Iterate over a string backward public static void main(String[] args) { String s = "Reverse String"; Field field = null; try { field = String.class.getDeclaredField("value"); } catch (NoSuchFieldException e) { e.printStackTrace(); } field.setAccessible(true); char[] chars = new char[0]; try { chars = (char[]) field.get(s); } catch (IllegalAccessException e) { e.printStackTrace(); } for (int i = chars.length - 1; i >= 0; i--) { System.out.print(chars[i]); } } } |
That’s all about iterating over a string backward in Java.
Related Post:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)