views:

192

answers:

4

I'm trying to write the equivalent of strchr, 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?

A: 

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).

Dave DeLong
A: 
Boolean nsstrchr(NSString* s, char c)
{
    NSString *tmps = [NSString stringWithFormat: @"%c", c];
    NSRange rg = [s rangeOfString: tmps];
    return rg.location != NSNotFound;
}
Isaac
A: 

Several simplifications.

  1. Use [s rangeOfString:tmps] to eliminate the character set.
  2. The character set can be created with [NSCharacterSet characterSetWithRange:NSMakeRange(c, 1)], so you don't need to create tmps
  3. strchr([s UTF8String], c) — assuming c is an ASCII character, and the returned pointer won't escape the function (there's a risk the pointer becomes dangling).
KennyTM
+2  A: 

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...
}
mipadi
@OP: Also note the use of `BOOL` instead of `Boolean` for Objective-C (soz, pedantics).
Wevah