John Erck
John Erck

Reputation: 9528

Objective C: What's the easiest way to determine if a substring exists within an NSString?

In PHP (which is what I'm most familiar with) it's a one line expression:

strpos('abc', 'b') !== false

What's the Objective C equivalent?

Upvotes: 1

Views: 1221

Answers (3)

Jeffery Thomas
Jeffery Thomas

Reputation: 42578

I think categories can be use to package up pieces of functionality like this very nicely.

@interface NSString (ContainsString)
- (BOOL)containsString:(NSString *)string;
@end

@implementation NSString (ContainsString)
- (BOOL)containsString:(NSString *)string
{
    NSRange range = [self rangeOfString:string options:NSCaseInsensitiveSearch];
    return range.location != NSNotFound;
}
@end

When used, it makes the meaning very clear.

if ([@"this is a string" containsString:@"a string"]) {
    …
}

In most projects this would be a part of a larger string method category and not it's own one-method category.

Upvotes: 3

Dan F
Dan F

Reputation: 17732

- (NSRange)rangeOfString:(NSString *)aString

Return Value An NSRange structure giving the location and length in the receiver of the first occurrence of aString. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

You can find more helpful string manipulation functions in the NSString Class Reference

Upvotes: 0

Parag Bafna
Parag Bafna

Reputation: 22930

[@"abc" rangeOfString:@"b"].location != NSNotFound

Upvotes: 7

Related Questions