当主字符串为nil且substring不是nil时,iOS rangeofString会做什么?

时间:2016-05-12 10:34:16

标签: ios nsstring

NSString *result = nil;
if([result rangeOfString:@"SUCCESS"].location != NSNotFound)
{
    NSLog(@"Location: %lu", [result rangeOfString:@"SUCCESS"].location);
    NSLog(@"Length: %lu", [result rangeOfString:@"SUCCESS"].length);
}
else{
    NSLog(@"NULL found:  %@", result);
}

此代码显示输出:

2016-05-12 18:51:44.589 TestProject[21666:207505] Location: 0

2016-05-12 18:51:44.590 TestProject[21666:207505] Length: 0

实际上它应该显示输出:

NULL found:  (null)

请解释输出的原因

2 个答案:

答案 0 :(得分:0)

通过以下链接,我对此类问题有了很好的解释:

How do I check if a string contains another string in Objective-C?

特别是你可以阅读@ ucangetit的答案。

你可以按照这两个功能......

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if(otherString && [string rangeOfString:otherString].length)
        return YES;
    else
        return NO;
}

或简单:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    return (otherString && [string rangeOfString:otherString].length);
}

答案 1 :(得分:0)

在我看来,如果range.length == 0 =>找不到。

NSString *result = nil;
NSRange range = [result rangeOfString:@"SUCCESS"];//location=0, length=0
if(range.length > 0) //Found
{
    NSLog(@"Location: %lu", range.location);
    NSLog(@"Length: %lu", range.length);
}