NSString indexOf in Objective-C

Use -[NSString rangeOfString:]:

- (NSRange)rangeOfString:(NSString *)aString;

Finds and returns the range of the first occurrence of a given string within the receiver.


If you want just know when String a contains String b use my way to do this.

#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)

//using 
NSString a = @"PUC MINAS - BRAZIL";

NSString b = @"BRAZIL";

if( contains(a,b) ){
    //TO DO HERE
}

This is less readable but improves performance


I wrote a category to extend original NSString object. Maybe you guys can reference it. (You also can see the article in my blog too.)

ExtendNSString.h:

#import <Foundation/Foundation.h>

@interface NSString (util)

- (int) indexOf:(NSString *)text;

@end

ExtendNSStriing.m:

#import "ExtendNSString.h"

@implementation NSString (util)

- (int) indexOf:(NSString *)text {
    NSRange range = [self rangeOfString:text];
    if ( range.length > 0 ) {
        return range.location;
    } else {
        return -1;
    }
}

@end