如何获取NSString
中的子字符串的位置/索引?
我以下列方式找到位置。
NSRange range = [string rangeOfString:searchKeyword];
NSLog (@"match found at index:%u", range.location);
当index:2147483647
是searchKeyword
中的子字符串时,会返回string
。
我如何获得像20
或5
这样的索引值?
答案 0 :(得分: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);
}
答案 1 :(得分: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];
这可能会对你有帮助....