21

内の部分文字列の位置/インデックスを取得するにはどうすればよいNSStringですか?

私は次の方法で場所を見つけています。

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

これは、が 内の部分文字列であるindex:2147483647 場合に返されます。searchKeywordstring

どうすればそのようなインデックス値を取得できます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 に答える