returning all index of a character in a NSString
IS there a method 开发者_运维问答that would return all the index of the occurences of the letter 'a' in a NSString lets say? Tried looking at the documentation and there seems that there isn't any. So I might have to break the NSString to an NSArray of chars and iterate?
Try [NSRegularExpression enumerateMatchesInString:options:range:usingBlock:]. Or indeed, any of the other NSRegularExpression matching methods. They won't return an NSIndexSet - it'll be an array of NSTextChecking objects - but you can quite easily get the index out of that.
Here's some (untested!) sample code:
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
}
It's actually more efficient to use enumerateMatchesInString, but I don't know how familiar you are with Blocks, so I opted for the more common fast enumeration of an NSArray.
Update: the same code using 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
}];
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;
}
Here searching for the substring Brown and Location of the substring is stored in the array countloc
精彩评论