Back
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?
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);}
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);
}
31k questions
32.8k answers
501 comments
693 users