2017-04-24 2 views
0

J'essaye de retourner l'index d'un mot dans une chaîne mais ne peux pas trouver une manière de traiter le cas où il n'est pas trouvé. Le suivi ne fonctionne pas parce que rien ne fonctionne. Avoir essayé toutes les combinaisons de int, NSInteger, NSUInteger, etc, mais ne peut pas trouver un compatible avec nil. Est-ce qu'il y a un moyen de faire ça? Merci pourIOS/Objective-C: Trouver l'index du mot dans la chaîne

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

Il suffit de regarder la documentation https://developer.apple.com/reference/foundation/nsarray/1417076-indexofobject: * "Si aucune les objets du tableau sont égaux à un objet, renvoie NSNotFound. "* –

Répondre

1

utilisation NSNotFound qui est ce que indexOfObject: retournera si word ne se trouve pas dans 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; 
    } 
} 

Maintenant lorsque vous appelez findIndexOfWord:inString:, vérifier le résultat de NSNotFound pour déterminer si elle a réussi ou non.

Votre code peut effectivement être écrit beaucoup plus facile que:

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

    return [substrings indexOfObject: word]; 
}