简体   繁体   中英

Index of a character from the NSString in iOS

我有一个NSString例如"This is my question" 。我想找到字符/子字符串"i"所有索引,即在这种情况下,如果索引从0开始,那么我想要2,5,16作为答案。

The other answer is a bit of an overkill. Why don't you simply iterate over the characters like this:

NSString *x = @"This is my question";

for (NSUInteger i=0;i<[x length];i++)
{
    if ([x characterAtIndex:i]=='i')
    {
        NSLog(@"found: %d", i);
    }
}

It outputs exactly your positions:

found: 2
found: 5
found: 16

I'd like suggest my solution. It is like this:

NSString* str = @"This is my question";
NSArray* arr = [str componentsSeparatedByString: @"i"];
NSMutableArray* marr = [NSMutableArray arr];
NSInteger cnt = 0;
for (NSInteger i = 0; i < ([arr count]); i++)
{
    NSString* s = [arr objectAtIndex: i];
    cnt += [s length];
    [marr addObject: [NSNumber numberWithInt: cnt]];
    cnt += [@"i" length];
}

NSLog(@"%@", [marr description]);

On console: 2 5 16

Using NSRange and loop and with some string manipulation you can easily do it.

        NSString *string = @"This is my question";
        NSString *substring = @"i";

        NSRange searchRange = NSMakeRange(0,string.length);
        NSRange foundRange;
        while (searchRange.location < string.length)
        {
            searchRange.length = string.length-searchRange.location;
            foundRange = [string rangeOfString:substring options:nil range:searchRange];
            if (foundRange.location != NSNotFound)
            {
                // found an occurrence of the char
                searchRange.location = foundRange.location+foundRange.length;
                NSLog(@"Location of '%@' is %d",substring,searchRange.location-1);
            }
        }

EDIT

Using NSRegularExpression and NSRange you can do like this.

NSString *string = @"This is my question";
NSString *substring = @"i";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:substring
                                                                       options:0
                                                                         error:NULL];

[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length])
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                         NSRange range = [result range];
                         NSLog(@"Location of '%@' is %d",substring, range.location);
                     }];

output is

Location of 'i' is 2
Location of 'i' is 5
Location of 'i' is 16

I don't know is there any built-in functions available for doing this. You can use this method:

- (NSMutableArray *)indexOfCharacter:(char)c inString:(NSString*)string
{

    NSMutableArray *returnArray = [[NSMutableArray alloc] init];
    for(int i=0;i<string.length;i++)
    {
        if(c == [string characterAtIndex:i])
        {
           [returnArray addObject:[NSNumber numberWithInt:i]];
        }
    }
    return returnArray;
}

This is my attempt at a no loop code of getting what you want. I coded this blind, meaning not-tested etc. Its basically a recursive function, but I think it gets you the general idea.

- (NSArray *)getAllEyes:(NSString *)s index:(int)index) {
    if (!s || s.length <= 0 || index >= s.length) return [NSArray new];
    NSRange *r = [s rangeOfString(@"i") options:NSLiteralSearch range:NSMakeRange(index, s.length - index)];
    if (r.location == NSNotFound) {
        return [NSArray new];
    } else {
        NSMutableArray *array = [NSMutableArray new];
        [array addObject:@(r.location)];
        [array addObjectsFromArray:[self getAllEyes:s index:r.location + 1]];
        return array;
    }    
}

// usage:

NSArray *allEyes = [self getAllEyes:@""];
for (NSNumber *n in allEyes) {
    NSLog(@"i = %@", n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM