How do I apply the for-each loop to every character in a String?
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
The easiest way to for-each every char
in a String
is to use toCharArray()
:
for (char ch: "xyz".toCharArray()) {
}
This gives you the conciseness of for-each construct, but unfortunately String
(which is immutable) must perform a defensive copy to generate the char[]
(which is mutable), so there is some cost penalty.
From the documentation:
[
toCharArray()
returns] a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
There are more verbose ways of iterating over characters in an array (regular for loop, CharacterIterator
, etc) but if you're willing to pay the cost toCharArray()
for-each is the most concise.
Another useful solution, you can work with this string as array of String
for (String s : "xyz".split("")) {
System.out.println(s);
}