Is there anything similar to an indexOf
function in the NSString objects?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With