-4

I am trying to create a for-each loop in Java that iterates on every character in a string. When I try to do this I get an error in NetBeans:

for-each not applicable to expression type
required:array or java.lang.Iterable, found java.lang.String

This is the Java code on which I get an error:

for(char c : fen){
}

fen is a String

I am trying to understand the source code of a game writen in C# and the foreach loop there worked:

foreach(char in fen){}
Perception
  • 79,279
  • 19
  • 185
  • 195
user1146440
  • 363
  • 1
  • 9
  • 19
  • 1
    http://stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a – mixel May 20 '12 at 12:17
  • Ok fine I will admit it.. It's because I wrote that particular par of the compiler... :-( – Thihara May 20 '12 at 12:44

4 Answers4

18

The compilation error message you get is pretty clear.

For-each loop is applicable for arrays and Iterable. String is not an array. It holds array of characters but it is not an array itself. String does not implement interface Iterable too.

If you want to use for-each loop for iteration over characters into the string you have to say:

for(char c : str.toCharArray()) {}

AlexR
  • 114,158
  • 16
  • 130
  • 208
2

String is not iteratable, try String#GetBytes():

for (byte b : str.getBytes(yourCharSet)) {

}
MByD
  • 135,866
  • 28
  • 264
  • 277
2

String is not iteratable. however you can convert String to char Array to iterate like this:

char[] fen = string.toCharArray();
for(char c : fen){
   //do your work
}
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
1

for-each loop wont work as you expected. For reference http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

char[] fen = //define array here
for(char c : fen){
}
Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90