How do I apply the for-each loop to every character in a String?

Lyndon White picture Lyndon White · Mar 16, 2010 · Viewed 450.4k times · Source

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?

Answer

polygenelubricants picture polygenelubricants · Mar 16, 2010

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.