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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The easiest way to for-each every
charin aStringis to usetoCharArray():This gives you the conciseness of for-each construct, but unfortunately
String(which is immutable) must perform a defensive copy to generate thechar[](which is mutable), so there is some cost penalty.From the documentation:
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 costtoCharArray()for-each is the most concise.