返回NSString中字符的所有索引

时间:2011-08-02 07:05:53

标签: iphone objective-c ipad

是否有一种方法可以返回NSString中字母'a'出现的所有索引?试着查看文档,似乎没有。所以我可能不得不将NSString分解为一个字符的NSArray并迭代?

2 个答案:

答案 0 :(得分:0)

尝试[NSRegularExpression enumerateMatchesInString:options:range:usingBlock:]。或者实际上,任何其他NSRegularExpression匹配方法。它们不会返回NSIndexSet - 它将是一个NSTextChecking对象的数组 - 但你可以很容易地从中获取索引。

这是一些(未经测试的!)示例代码:

NSString* aString = @"Here's a string, that contains some letters a";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"a" options:0 error:NULL];
NSArray* matches = [regex matchesInString:aString options:0 range:NSMakeRange(0,[aString length])];
for(NSTextCheckingResult* i in matches) {
    NSRange range = i.range;
    NSUInteger index = range.location; //the index you were looking for!
    //do something here
}

使用enumerateMatchesInString实际上更有效率,但我不知道你对Blocks有多熟悉,所以我选择了更常见的NSArray快速枚举。

更新:使用Blocks的相同代码。

NSString* aString = @"Here's a string, that contains some letters a";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"a";
[regex enumerateMatchesInString:aString 
                        options:0 
                          range:NSMakeRange(0,[aString length])
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    NSRange range = result.range;
    NSUInteger index = range.location; //the index you were looking for
    //do work here

}];

答案 1 :(得分:0)

NSString *full_string=@"The Quick Brown Fox Brown";
    NSMutableArray *countloc=[[NSMutableArray alloc]init];
    int temp=0;
    int len=[full_string length];
    for(int i =0;i<[full_string length];i++)
    {
            NSRange range=[full_string rangeOfString:@"Brown" options:0 range:NSMakeRange(temp,len-1)];
            if(range.location<[full_string length])
            [countloc addObject:[NSString stringWithFormat:@"%d",range.location]];
            temp=range.location+1;
            len=[full_string length]-range.location;
            i=temp;

    }

在这里搜索子串Brown和 子字符串的位置存储在数组countloc