How to iterate through the characters of an NSString

后端 未结 3 909
孤街浪徒
孤街浪徒 2021-01-11 16:04
NSString *myStrings = @\"abcdefghijklmnopqrstuvwxyz\";

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

相关标签:
3条回答
  • 2021-01-11 16:25

    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]);
    }
    
    0 讨论(0)
  • 2021-01-11 16:29

    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]);
    
    0 讨论(0)
  • 2021-01-11 16:30

    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));
    
     }];
    
    0 讨论(0)
提交回复
热议问题