Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.9k points)

So I want to iterate for each character in a string.

So I thought:

for (char c : "xyz")

but I get a compiler error: foreach not applicable to expression type

How can I do this?

1 Answer

0 votes
by (46k points)

You need to convert the String object into an array of char using the toCharArray() method of the String class:

String str = "xyz";

char arr[] = str.toCharArray(); // convert the String object to array of char

// iterate over the array using the for-each loop.       

for(char c: arr){



Browse Categories