So I want to iterate for each character in a string.
So I thought:
for (char c : "xyz")
but I get a compiler error:
StackCharTester.java:20: foreach not applicable to expression type
How can I do this?
So I want to iterate for each character in a string.
So I thought:
for (char c : "xyz")
but I get a compiler error:
StackCharTester.java:20: foreach not applicable to expression type
How can I do this?
String s = "xyz";
for(int i = 0; i < s.length(); s++)
{
char c = s.charAt(i);
}
The easiest way to for-each every char
in a String
is to use toCharArray()
:
for (char ch: "xyz".toCharArray()) {
}
This gives you the conciseness of for-each construct, but unfortunately String
(which is immutable) must perform a defensive copy to generate the char[]
(which is mutable), so there is some cost penalty.
From the documentation:
[
toCharArray()
returns] a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
There are more verbose ways of iterating over characters in an array (regular for loop, CharacterIterator
, etc) but if you're willing to pay the cost toCharArray()
for-each is the most concise.
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);
}