Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString indexOf in Objective-C

Is there anything similar to an indexOf function in the NSString objects?

like image 279
Guido Avatar asked Nov 02 '08 03:11

Guido


3 Answers

Use -[NSString rangeOfString:]:

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

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

like image 152
Airsource Ltd Avatar answered Sep 23 '22 02:09

Airsource Ltd


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

like image 29
orafaelreis Avatar answered Sep 24 '22 02:09

orafaelreis


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
like image 19
firestoke Avatar answered Sep 22 '22 02:09

firestoke