子串在NSString中的位置

时间:2012-06-28 06:54:49

标签: iphone objective-c ios xcode ios4

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

我以下列方式找到位置。

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

index:2147483647searchKeyword中的子字符串时,会返回string

我如何获得像205这样的索引值?

2 个答案:

答案 0 :(得分:59)

2147483647NSNotFound相同,这意味着找不到您搜索的字符串(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];

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