I have to match the number of occurrences of n special characters in a string.
I thought to create an array with all these chars (they are 20+) and create a function to match each of them. I just have the total amount of special characters in the string, so I can make some math count on them.So in the example:
NSString *myString = @"My string #full# of speci@l ch@rs & symbols";
NSArray *myArray = [NSArr开发者_如何学运维ay arrayWithObjects:@"#",@"@",@"&",nil];
The function should return 5.
Would it be easier match the characters that are not in the array, take the string length and output the difference between the original string and the one without special chars?
Is this the best solution?NSString *myString = @"My string #full# of speci@l ch@rs & symbols";
//even in first continuous special letters it contains -it will return 8
//NSString *myString = @"#&#My string #full# of speci@l ch@rs & symbols";
NSArray *arr=[myString componentsSeparatedByCharactersInSet:[NSMutableCharacterSet characterSetWithCharactersInString:@"#@&"]];
NSLog(@"resulted string : %@ \n\n",arr);
NSLog(@"count of special characters : %i \n\n",[arr count]-1);
OUTPUT:
resulted string : (
"My string ",
full,
" of speci",
"l ch",
"rs ",
" symbols"
)
count of special characters : 5
You should utilize an NSRegularExpression, its perfect for your scenario. You can create one like this:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(#|&)" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];
Caveat: I ripped the code from the Apple Developer site. And I'm no regex guru so you will have to tweak the pattern. But you get the gist.
You should look also at NSRegularExpression
:
- (NSUInteger)numberOfCharacters:(NSArray *)arr inString:(NSString *)str {
NSMutableString *mutStr = @"(";
for(i = 0; i < [arr count]; i++) {
[mutStr appendString:[arr objectAtIndex:i]];
if(i+1 < [arr count]) [mutStr appendString:@"|"];
}
[mutStr appendString:@")"];
NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:mutStr options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger *occur = [regExnumberOfMatchesInString:str options:0 range:NSMakeRange(0, [string length])];
[mutStr release];
return occur;
}
Usage example:
NSString *myString = @"My string #full# of speci@l ch@rs & symbols";
NSArray *myArray = [NSArray arrayWithObjects:@"#",@"@",@"&",nil];
NSLog(@"%d",[self numberOfCharacters:myArray inString:myString]); // will print 5
精彩评论