NSString indexOf in Objective-C

Objective CCocoa

Objective C Problem Overview


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

Objective C Solutions


Solution 1 - 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.

Solution 2 - Objective C

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

Solution 3 - Objective C

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

Solution 4 - Objective C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuidoView Question on Stackoverflow
Solution 1 - Objective CAirsource LtdView Answer on Stackoverflow
Solution 2 - Objective CorafaelreisView Answer on Stackoverflow
Solution 3 - Objective CfirestokeView Answer on Stackoverflow
Solution 4 - Objective CWilliam FalconView Answer on Stackoverflow