Reputation: 47675
Is there anything similar to an indexOf
function in the NSString objects?
Upvotes: 56
Views: 61272
Reputation: 9813
I know it's late, but I added a category that implements this method and many others similar to javascript string methods
https://github.com/williamFalcon/WF-iOS-Categories
Upvotes: 1
Reputation: 2881
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
Upvotes: 29
Reputation: 1059
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
Upvotes: 19
Reputation: 32622
Use -[NSString rangeOfString:]
:
- (NSRange)rangeOfString:(NSString *)aString;
Finds and returns the range of the first occurrence of a given string within the receiver.
Upvotes: 91