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?
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);
}
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....
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