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?

3
  • 1
    Does this help? techotopia.com/index.php/… Commented Jul 13, 2012 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. Commented Jul 13, 2012 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): stackoverflow.com/questions/11439180/… Nobody should be writing code equal to some of the bad answers. Having the simple answer documented is ultimately a good thing. Commented Jul 13, 2012 at 18:54

3 Answers 3

7
[@"abc" rangeOfString:@"b"].location != NSNotFound
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.