IOS / Objective-C:在String中查找单词索引

时间:2017-04-24 14:38:13

标签: ios objective-c nsuinteger

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

1 个答案:

答案 0 :(得分:1)

使用NSNotFound indexOfObject:,如果在word中找不到substrings,则- (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]; } 的结果,以确定其是否成功。

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

prettyNum