What is the easiest/best/most correct way to iterate through the characters of a string in Java?
There are several ways you can iterate through the characters of a string in Java. Here are a few options:
- Using a
for
loop:
String str = "Hello";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// do something with c
}
- Using a
for-each
loop:
String str = "Hello";
for (char c : str.toCharArray()) {
// do something with c
}
- Using an iterator:
String str = "Hello";
for (Iterator<Character> it = str.chars().mapToObj(c -> (char)c).iterator(); it.hasNext(); ) {
char c = it.next();
// do something with c
}
All of these methods are correct and which one you choose will depend on your personal preference and the context in which you are using it.