0 votes
1 view
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 (46.1k 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);

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...