0

What's the best way to iterate NSString? Code like following:

int len = str.length;
for (int i = 0; i < len; ++i)
{
    unichar c = [str characterAtIndex:i];
    // do something with c
}

looks ugly for me. I'd prefer something like

// does not compile, unfortunately
for (unichar c in str)
{
    // do something with c
}

Is there any way to write it more gracefully than my first code snippet?

Nick
  • 3,205
  • 9
  • 57
  • 108
  • What are you trying to do with the string? There are a lot of built in functions that let you skip simple string iterations. – DogEatDog Jul 12 '12 at 01:37
  • In case anyone lands in this page as I did, check this [answer](http://stackoverflow.com/questions/4158646/most-efficient-way-to-iterate-over-all-the-chars-in-an-nsstring) – Rodrigo Gonzalez Mar 04 '17 at 03:07

1 Answers1

0
for(NSString *subString in yourString){
    NSLog("The Substring is: %@", subString);
    // do anything you want with the substring in this loop
}

This must work(if not, you can define your string as NSDictionary and try again)

ilhan çetin
  • 383
  • 5
  • 19