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

时间:2023-01-25 19:20:16

I am trying to return the index of a word in a string but can't figure out a way to handle case where it is not found. Following does not work because nil does not work. Have tried every combination of int, NSInteger, NSUInteger etc. but can't find one compatible with nil. Is there anyway to do this? Thanks for

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

#1


1  

Use NSNotFound which is what indexOfObject: will return if word is not found in substrings.

使用NSNotFound,这是indexOfObject:如果在子字符串中找不到单词将返回。

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

Now when you call findIndexOfWord:inString:, check the result for NSNotFound to determine if it succeeded or not.

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

Your code can actually be written much easier as:

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

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

    return [substrings indexOfObject: word];
}

#1


1  

Use NSNotFound which is what indexOfObject: will return if word is not found in substrings.

使用NSNotFound,这是indexOfObject:如果在子字符串中找不到单词将返回。

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

Now when you call findIndexOfWord:inString:, check the result for NSNotFound to determine if it succeeded or not.

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

Your code can actually be written much easier as:

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

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

    return [substrings indexOfObject: word];
}