Aswathy Bose
Aswathy Bose

Reputation: 4289

Index of a character from the NSString in iOS

I have an NSString for example "This is my question".I want to find all the indices of the character/substring "i" ie In this case If index starts from 0,then I want 2,5,16 as my answer.

Upvotes: 2

Views: 11080

Answers (5)

stosha
stosha

Reputation: 2148

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

Upvotes: 1

kailoon
kailoon

Reputation: 2069

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);
}

Upvotes: 0

βhargavḯ
βhargavḯ

Reputation: 9836

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

Upvotes: 0

Midhun MP
Midhun MP

Reputation: 107121

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;
}

Upvotes: 0

Christoph Wimberger
Christoph Wimberger

Reputation: 136

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

Upvotes: 4

Related Questions