Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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:

MyClass.java:20: 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){

    System.out.println(c);

}

Browse Categories

...