IOS/Objective-C: 查找字符串中单词的索引

IOS/Objective-C: Find Index of word in String

我正在尝试 return 字符串中单词的索引,但无法找到处理未找到该单词的情况的方法。以下不起作用,因为 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;
    }
}

使用 NSNotFound 如果 substrings 中找不到 wordindexOfObject: 将 return 使用 NSNotFound

- (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];
}