21

如何获取子字符串的位置/索引NSString

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

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

这将返回index:2147483647 whensearchKeyword是 内的子字符串string

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

4

2 回答 2

62

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);
}
于 2012-06-28T06:56:40.970 回答
10
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];

这可能会帮助你....

于 2012-06-28T07:14:09.593 回答