子串在NSString中的位置

Sha*_*man 19 iphone xcode objective-c ios4 ios

我如何获得一个子串的位置/索引NSString

我通过以下方式找到位置.

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

这将返回index:2147483647 何时searchKeyword是子字符串string.

我怎么能得到这样的索引值205那样?

Lil*_*ard 59

2147483647是一样的NSNotFound,这意味着searchKeyword找不到你搜索的字符串().

NSRange range = [string rangeOfString:searchKeyword];
if (range.location == NSNotFound) {
    NSLog(@"string was not found");
} else {
    NSLog(@"position %lu", (unsigned long)range.location);
}
Run Code Online (Sandbox Code Playgroud)


Abh*_*hek 9

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];
Run Code Online (Sandbox Code Playgroud)

这可能会对你有所帮助....