How do I apply the for-each loop to every character in a String?

后端 未结 9 1778
南笙
南笙 2020-11-30 17:32

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

So I thought:

for (char c : \"xyz\")

but I get a compiler error:



        
9条回答
  •  孤街浪徒
    2020-11-30 18:26

    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);
    }
    

提交回复
热议问题