简体   繁体   English

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

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

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. 由于nil不起作用,因此以下方法不起作用。 Have tried every combination of int, NSInteger, NSUInteger etc. but can't find one compatible with nil. 已经尝试了int,NSInteger,NSUInteger等的每种组合,但是找不到与nil兼容的组合。 Is there anyway to do this? 反正有这样做吗? Thanks for 感谢

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

Use NSNotFound which is what indexOfObject: will return if word is not found in substrings . 使用NSNotFound ,如果在substrings找不到wordindexOfObject:将返回。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM