1

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?

John Erck
  • 9,478
  • 8
  • 61
  • 71
  • 1
    Does this help? http://www.techotopia.com/index.php/Working_with_String_Objects_in_Objective-C#Searching_for_a_Substring – jeffff Jul 13 '12 at 18:42
  • The Cocoa classes are fairly well-documented. You're obviously encouraged to take a look at them any time you need something. – zneak Jul 13 '12 at 18:43
  • @zneak I totally agree but a simple question isn't necessarily a bad question - especially considering how contrived some people's solutions are to simple questions. Documenting good answers to simple questions is of benefit to the community. Proof in point (a post I made the other day): http://stackoverflow.com/questions/11439180/whats-the-easiest-way-to-remove-empty-nsstrings-from-an-nsarray Nobody should be writing code equal to some of the bad answers. Having the simple answer documented is ultimately a good thing. – John Erck Jul 13 '12 at 18:54

3 Answers3

7
[@"abc" rangeOfString:@"b"].location != NSNotFound
Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
3

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.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
0
- (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

Dan F
  • 17,654
  • 5
  • 72
  • 110