iosobjective-cnsuinteger

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. 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

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

Solution

  • Use NSNotFound which is what indexOfObject: will return if word is not found in 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;
        }
    }
    

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

    Your code can actually be written much easier as:

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