2

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.

UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
Aswathy Bose
  • 4,279
  • 4
  • 32
  • 44
  • 3
    OK, what do you need help with? Post what you have tried so far. – rmaddy May 21 '13 at 05:05
  • 1
    i guess you are looking for [this](http://stackoverflow.com/questions/938095/nsstring-number-of-occurrences-of-a-character), surely you will find your answer after refering this post – Dipen Panchasara May 21 '13 at 05:11
  • possible duplicate of [NSString number of occurrences of a character](http://stackoverflow.com/q/938095) – jscs May 21 '13 at 06:10

5 Answers5

4

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
1

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

Muhammad Waqas
  • 904
  • 2
  • 10
  • 21
stosha
  • 2,108
  • 2
  • 27
  • 29
0

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
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
0

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;
}
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0

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);
}
kailoon
  • 2,131
  • 1
  • 18
  • 33