How do I apply the for-each loop to every character in a String?
So I want to iterate for each character in a string.
So I thought:
for (char c : "xyz")
but I get a compiler error:
MyClass.java:20: foreach not applicable to expression type
How can I do this?
Solution 1:
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.
Solution 2:
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
Solution 3:
Another useful solution, you can work with this string as array of String
for (String s : "xyz".split("")) {
System.out.println(s);
}