Languages
[Edit]
EN

Java - iterate string backwards

0 points
Created by:
Wallace
366

In this article, we would like to show you how to iterate string backwards in Java.

Quick solution:

String text = "ABC";

for (int i = text.length() - 1; i >= 0; i--) {
    System.out.print(text.charAt(i));
}

 

1. Practical example using for loop

In this example, we use simple for loop to iterate the text string backwards.

public class Example {

    public static void main(String[] args) {
        String text = "ABC";

        for (int i = text.length() - 1; i >= 0; i--) {
            System.out.print(text.charAt(i));
        }
    }
}

Output:

CBA

2. Using String split() method

In this example, we use String split() method with empty string ("") as a separator to split the text string into array of strings (letters). Then we iterate through the letters array using simple for loop.

public class Example {

    public static void main(String[] args) {
        String text = "ABC";

        String[] letters = text.split("");

        for (int i = letters.length - 1; i >= 0; i--) {
            System.out.print(letters[i]);
        }
    }
}

Output:

CBA

3. Converting string to character array

In this example, we create new StringBuilder object from the text string, reverse it and convert to characters array. Then we simply iterate over the characters array using enhanced for loop.

public class Example {

    public static void main(String[] args) {
        String text = "ABC";

        char[] characters = new StringBuilder(text)
                .reverse()
                .toString()
                .toCharArray();

        for (char ch : characters) {
            System.out.print(ch);
        }
    }
}

Output:

CBA

4. Using iterator

 In this example, we use the CharacterIterator with its last() and previous() methods to iterate the text string backwards.

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Example {

    public static void main(String[] args) {
        String text = "ABC";

        CharacterIterator iterator = new StringCharacterIterator(text);

        char character = iterator.last();
        while (character != CharacterIterator.DONE) {
            System.out.print(character);
            character = iterator.previous();
        }
    }
}

Output:

CBA
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join