Date: 2013nov7
Update: 2025sep29
Language: Java
Q. Java: How can I iterate through a String
A. There are several resaonable ways.
Shown as a full example:
class Demo {
public static final void main(String []args) {
final String s = "Hello World";
// Use charAt()
System.out.print("method1: ");
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
System.out.print(c + " ");
}
System.out.println();
// Use toCharArray()
System.out.print("method2: ");
for (final char c : s.toCharArray()) {
System.out.print(c + " ");
}
System.out.println();
// Use getBytes()
System.out.print("method3: ");
for (final byte b : s.getBytes()) {
System.out.print((char)b + " ");
}
System.out.println();
}
}
Output:
method1: H e l l o W o r l d
method2: H e l l o W o r l d
method3: H e l l o W o r l d
Some guy compared all the possible ways for speed:
http://stackoverflow.com/questions/8894258/fastest-way-to-iterate-over-all-the-chars-in-a-string