EN
Java - iterate string backwards
0 points
In this article, we would like to show you how to iterate string backwards in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
3
for (int i = text.length() - 1; i >= 0; i--) {
4
System.out.print(text.charAt(i));
5
}
In this example, we use simple for loop to iterate the text
string backwards.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
6
for (int i = text.length() - 1; i >= 0; i--) {
7
System.out.print(text.charAt(i));
8
}
9
}
10
}
Output:
xxxxxxxxxx
1
CBA
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.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
6
String[] letters = text.split("");
7
8
for (int i = letters.length - 1; i >= 0; i--) {
9
System.out.print(letters[i]);
10
}
11
}
12
}
Output:
xxxxxxxxxx
1
CBA
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.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
6
char[] characters = new StringBuilder(text)
7
.reverse()
8
.toString()
9
.toCharArray();
10
11
for (char ch : characters) {
12
System.out.print(ch);
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
CBA
In this example, we use the CharacterIterator
with its last()
and previous()
methods to iterate the text
string backwards.
xxxxxxxxxx
1
import java.text.CharacterIterator;
2
import java.text.StringCharacterIterator;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
String text = "ABC";
8
9
CharacterIterator iterator = new StringCharacterIterator(text);
10
11
char character = iterator.last();
12
while (character != CharacterIterator.DONE) {
13
System.out.print(character);
14
character = iterator.previous();
15
}
16
}
17
}
Output:
xxxxxxxxxx
1
CBA