Skip to content

December 8, 2011

Search for a substring in a string in Cocoa

by noise

To search for a substring in a string in Cocoa, use the following code:

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
    @autoreleasepool {
        NSString *string1 = @"This is just a string";
        NSString *string2 = @"This is another string";
        NSRange range1 = [string1 rangeOfString:@"just"];
        NSRange range2 = [string2 rangeOfString:@"test"];
        if (range1.location != NSNotFound )
            NSLog(@"String string1 contains word 'just'");
            NSLog(@"String string1 does not contain word 'just'");
        if (range2.location != NSNotFound )
            NSLog(@"String string2 contains word 'test'");
            NSLog(@"String string2 does not contain word 'test'");
    return 0;
Read more from Cocoa

Leave a Reply


Note: HTML is allowed. Your email address will never be published.

Subscribe to comments