Iterate over a String Backwards in Java

In this post, we will discuss various methods to iterate over a String backwards in Java.


 

1. For loop

We can use a simple for loop to process each character of the String in reverse direction. This approach is very effective for strings having less characters.

Java

Download   Run Code

2. Convert to Character array

In this approach, we initally reverse the string. Then we convert the reversed String to a character array by using String.toCharArray() function. Finally, we iterate the char[] using for-each loop as shown below:

Java

Download   Run Code

3. Using CharacterIterator

We can also use CharacterIterator interface that provides bidirectional iteration for a String.

Java

Download   Run Code

4. Using String.Split() –

String.split() splits the specified string and returns an array of strings created by splitting this string .

Java

Download   Run Code

5. Using Guava –

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 List.listIterator(index) method to get a ListIterator over the elements in a list starting from specified position in the list.

Java

Download   Run Code

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 below code and search one with type char[].

Java

Download   Run Code

 
Related Post: Iterate over Characters of String in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz