• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for-each construct

 
bryan lim
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It can also be an instance of java.lang.Iterable
 
bryan lim
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so not for String?
 
Sridhar Santhanakrishnan
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont think it works for Strings. But probably one of the ranchers has a different idea.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you!
 
dhiraj sardana
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you. now i understand
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
bryan lim
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thank you. i was considering the efficiency as well. your post comes in handy!

thank you everyone! javaranch is super!!
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic