天天看點

查找某關鍵字在目标字元串中出現次數及位置

//查找某關鍵字在目标字元串中出現次數及位置
- (NSMutableArray *)filterString
{
    NSString *str = @"abcdefg&123_我們haha,.123hf 123";
    NSLog(@"%lu~~%i",strlen((char *)[str UTF8String]),[str length]);
    NSRange range={0,0};
    NSMutableArray *arr = [[NSMutableArray alloc]initWithCapacity:0];
    //每次指針偏移量
    int loc = 0;
    while (range.location<[str length]) 
    {
        loc += range.location+range.length;
        str = [str substringFromIndex:(range.location+range.length)];
        NSLog(@"%@",str);
        range = [str rangeOfString:@"123"];
        if(range.location==NSNotFound)
            break;
        [arr addObject:[NSNumber numberWithInt:(loc+range.location)]];
        NSLog(@"%i,%i",loc+range.location,range.length);
    }
    return [arr autorelease];
}      

繼續閱讀