11
NSString *myStrings = @"abcdefghijklmnopqrstuvwxyz";

How could I iterate each of the letters (a, b, c, d, e, etc..) in an Objective-C for loop?

Quintin Willison
  • 610
  • 6
  • 13
Saturn
  • 17,888
  • 49
  • 145
  • 271

3 Answers3

22

One way is to use a simple for-loop:

for (NSInteger charIdx=0; charIdx<myStrings.length; charIdx++)
    // Do something with character at index charIdx, for example:
    NSLog(@"%C", [myStrings characterAtIndex:charIdx]);
pythonquick
  • 10,789
  • 6
  • 33
  • 28
6

I would suggest to use getCharacters:range: instead. You get the raw unicode array with one object call and can iterate over the result. The output is the same, but it's faster.

NSString *inputString = @"abcdefghijklmnopqrstuvwxyz";
NSUInteger length = inputString.length;
unichar buffer[length+1];
// do not use @selector(getCharacters:) it's unsafe
[inputString getCharacters:buffer range:NSMakeRange(0, length)];

for(int i = 0; i < length; i++)
{
    NSLog(@"%C", buffer[i]);
}
Eike
  • 620
  • 4
  • 6
  • unichar is the type for utf-16: https://developer.apple.com/documentation/foundation/unichar – Eike Jun 15 '17 at 19:22
  • 1
    If you are wondering what this is good for, it's a required in/out parameter for getCharacters:range: https://developer.apple.com/documentation/foundation/nsstring/1408720-getcharacters?language=objc – Eike Jun 15 '17 at 19:24
3

Enumerate substrings of NSString characters with a block

NSString *characters = @"abcdefghijklmnopqrstuvwxyz";
[characters enumerateSubstringsInRange:NSMakeRange(0, characters.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {

     NSLog(@"substring: %@ substringRange: %@, enclosingRange %@", substring, NSStringFromRange(substringRange), NSStringFromRange(enclosingRange));

 }];
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93