Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position of a Substring in NSString

How I can get the position/Index of a substring within an NSString?

I am finding the location in the following way.

NSRange range = [string rangeOfString:searchKeyword];
NSLog (@"match found at index:%u", range.location);

This returns index:2147483647 when searchKeyword is a substring within string.

How i can get the index value like 20 or 5 like that?

like image 611
Shaheen Rehman Avatar asked Jun 28 '12 06:06

Shaheen Rehman


2 Answers

2147483647 is the same thing as NSNotFound, which means the string you searched for (searchKeyword) wasn't found.

NSRange range = [string rangeOfString:searchKeyword];
if (range.location == NSNotFound) {
    NSLog(@"string was not found");
} else {
    NSLog(@"position %lu", (unsigned long)range.location);
}
like image 104
Lily Ballard Avatar answered Nov 13 '22 09:11

Lily Ballard


NSString *searchKeyword = @"your string";

NSRange rangeOfYourString = [string rangeOfString:searchKeyword];

if(rangeOfYourString.location == NSNotFound)
{
     // error condition — the text searchKeyword wasn't in 'string'
}
else{
     NSLog(@"range position %lu", rangeOfYourString.location);
}

NSString *subString = [string substringToIndex:rangeOfYourString.location];

may this will help you....

like image 32
Abhishek Avatar answered Nov 13 '22 08:11

Abhishek