EN
Java - iterate through string
0 points
In this article, we would like to show you how to iterate through string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
3
for (int i = 0; i < text.length(); i++) {
4
System.out.print(text.charAt(i));
5
}
In this example, we iterate through the text
string and print each character.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) throws Exception {
4
String text = "ABC";
5
6
for (int i = 0; i < text.length(); i++) {
7
System.out.print(text.charAt(i));
8
}
9
}
10
}
Output:
xxxxxxxxxx
1
ABC
In this example, we use String toCharArray()
method to convert text
String to the characters
array. Then we use enhanced for-loop to iterate through the array.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) throws Exception {
4
String text = "ABC";
5
6
char[] characters = text.toCharArray();
7
8
for (char ch : characters) {
9
System.out.print(ch);
10
}
11
}
12
}
Output:
xxxxxxxxxx
1
ABC
In this example, we use String split()
method to convert text
String to the letters
array. Then we use enhanced for-loop to iterate through the array.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) throws Exception {
4
String text = "ABC";
5
6
String[] letters = text.split("");
7
8
for (String letter : letters) {
9
System.out.print(letter);
10
}
11
}
12
}
Output:
xxxxxxxxxx
1
ABC
In this example, we use StringCharacterIterator
class to iterate through the text
string.
xxxxxxxxxx
1
import java.text.CharacterIterator;
2
import java.text.StringCharacterIterator;
3
4
public class Example {
5
6
public static void main(String[] args) throws Exception {
7
String text = "ABC";
8
CharacterIterator iterator = new StringCharacterIterator(text);
9
10
while (iterator.current() != CharacterIterator.DONE)
11
{
12
System.out.print(iterator.current());
13
iterator.next();
14
}
15
}
16
}
Output:
xxxxxxxxxx
1
ABC