| Author |
for-each construct
|
bryan lim
Ranch Hand
Joined: Dec 26, 2008
Posts: 140
|
|
hi all,
can i use for-each loop on String?
like for( Char c : String) ? must it always be an array?
|
 |
Sridhar Santhanakrishnan
Ranch Hand
Joined: Mar 20, 2007
Posts: 317
|
|
|
It can also be an instance of java.lang.Iterable
|
 |
bryan lim
Ranch Hand
Joined: Dec 26, 2008
Posts: 140
|
|
|
so not for String?
|
 |
Sridhar Santhanakrishnan
Ranch Hand
Joined: Mar 20, 2007
Posts: 317
|
|
|
I dont think it works for Strings. But probably one of the ranchers has a different idea.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
No, you can't use it for Strings. But there is a String method which can convert the String to an array, and it will work on that array.
|
 |
bryan lim
Ranch Hand
Joined: Dec 26, 2008
Posts: 140
|
|
|
thank you!
|
 |
dhiraj sardana
Greenhorn
Joined: Jan 21, 2009
Posts: 5
|
|
You can only iterate an array or an object which is an instance of java.lang.iterable through for each loop.But you can iterate over string by first coverting it to char array like:
String str = "Hello world";
char[] chArr = str.toCharArray();
for(char c:chArr)
{
System.out.println(c);
}
|
 |
bryan lim
Ranch Hand
Joined: Dec 26, 2008
Posts: 140
|
|
|
thank you. now i understand
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
Please don't simply give out answers like that, dhiraj sardana. Ytbryan Lim would have remembered a lot better for working out the methods, rather than being told what to do.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Don't forget that toCharArray() creates a new array. This takes memory, and time to fill its contents. Using a basic for-loop using length() and charAt() is better:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
bryan lim
Ranch Hand
Joined: Dec 26, 2008
Posts: 140
|
|
ok thank you. i was considering the efficiency as well. your post comes in handy!
thank you everyone! javaranch is super!!
|
 |
 |
|
|
subject: for-each construct
|
|
|