strchr in objective C?
I'm trying to write the equivalent of s开发者_StackOverflowtrchr, but with NSStrings... I've currently got this:
Boolean nsstrchr(NSString* s, char c)
{
NSString *tmps = [NSString stringWithFormat: @"%c", c];
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString: tmps];
NSRange rg = [s rangeOfCharacterFromSet: cSet];
return rg.location != NSNotFound;
}
This seems needlessly complex... Is there a way to do this (preferably, one that doesn't involve turning the NSString into a cstring which doubles the run time, or writing it myself using characterAtIndex:... Am I missing some obvious method in the NSString description?
KennyTM has already noted (in a comment) that you can use -[NSString rangeOfString:]
instead of -[NSString rangeOfCharacterFromSet]
. I don't mean to steal his helpful answer, but I wanted to point out that you can wrap this up in a category on NSString
to make it easier to use:
@interface NSString (AdditionalStringOps)
- (BOOL) containsCharacter:(char) c;
@end
@implementation NSString (AdditionalStringOps)
- (BOOL) containsCharacter:(char) c
{
NSString *tmp = [NSString stringWithFormat:@"%c", c];
return [self rangeOfString:tmp].location != NSNotFound;
}
@end
And then you can use it like so:
if ([myString containsCharacter:'A']) {
// Do stuff...
}
As @KennyTM mentioned, use rangeOfString:
. If you really have to deal with stuff on the char
level, you can pull out the char*
via -UTF8String
(or -cStringUsingEncoding:
) and then search for your character in there like you would on any other char*
(probably by using strchr
).
Boolean nsstrchr(NSString* s, char c)
{
NSString *tmps = [NSString stringWithFormat: @"%c", c];
NSRange rg = [s rangeOfString: tmps];
return rg.location != NSNotFound;
}
Several simplifications.
- Use
[s rangeOfString:tmps]
to eliminate the character set. - The character set can be created with
[NSCharacterSet characterSetWithRange:NSMakeRange(c, 1)]
, so you don't need to createtmps
strchr([s UTF8String], c)
— assumingc
is an ASCII character, and the returned pointer won't escape the function (there's a risk the pointer becomes dangling).
精彩评论