2017-04-24 67 views
0

我想返回字符串中某個單詞的索引,但無法找出處理找不到的方式。以下不起作用,因爲零不起作用。已經嘗試了int,NSInteger,NSUInteger等的每個組合,但找不到與nil兼容的一個組合。無論如何要做到這一點?感謝iOS/Objective-C:查找字符串索引

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

試想一下,在文檔https://developer.apple.com/reference/foundation/nsarray/1417076-indexofobject:*「如果沒有數組中的對象等於anObject,返回NSNotFound。「* –

回答

1

使用NSNotFound這是什麼indexOfObject:將返回如果wordsubstrings找到。

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