0

我正在尝试返回字符串中单词的索引,但无法找到一种方法来处理找不到它的情况。以下不起作用,因为 nil 不起作用。尝试了 int、NSInteger、NSUInteger 等的每一种组合,但找不到与 nil 兼容的组合。有没有办法做到这一点?感谢

-(NSUInteger) findIndexOfWord: (NSString*) word inString: (NSString*) string {
    NSArray *substrings = [string componentsSeparatedByString:@" "];

    if([substrings containsObject:word]) {
        int index = [substrings indexOfObject: word];
        return index;
    } else {
        NSLog(@"not found");
        return nil;
    }
}
4

1 回答 1

1

如果在 中找不到,则使用NSNotFoundwhichindexOfObject:将返回的内容。wordsubstrings

- (NSUInteger)findIndexOfWord:(NSString *)word inString:(NSString *)string {
    NSArray *substrings = [string componentsSeparatedByString:@" "];

    if ([substrings containsObject:word]) {
        int index = [substrings indexOfObject:word];
        return index; // Will be NSNotFound if "word" not found
    } else {
        NSLog(@"not found");
        return NSNotFound;
    }
}

现在,当您调用 时findIndexOfWord:inString:,检查结果NSNotFound以确定它是否成功。

您的代码实际上可以更容易地编写为:

- (NSUInteger)findIndexOfWord:(NSString *)word inString:(NSString *)string {
    NSArray *substrings = [string componentsSeparatedByString:@" "];

    return [substrings indexOfObject: word];
}
于 2017-04-24T14:41:03.417 回答