So I want to iterate for each character in a string.
So I thought:
for (char c : \"xyz\")
but I get a compiler error:
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
Unfortunately Java does not make String
implement Iterable<Character>
. This could easily be done. There is StringCharacterIterator
but that doesn't even implement Iterator
... So make your own:
public class CharSequenceCharacterIterable implements Iterable<Character> {
private CharSequence cs;
public CharSequenceCharacterIterable(CharSequence cs) {
this.cs = cs;
}
@Override
public Iterator<Character> iterator() {
return new Iterator<Character>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < cs.length();
}
@Override
public Character next() {
return cs.charAt(index++);
}
};
}
}
Now you can (somewhat) easily run for (char c : new CharSequenceCharacterIterable("xyz"))
...
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);
}