2015-07-22 80 views
1

我有一個有趣的小問題。所以,我需要創建一個if語句,可以檢測,如果有一個字後一個字一個數組檢查一個單詞後面是否有單詞(NSSTRING)

所以我的代碼是

NSArray *words = [texfield.text componentsSeparatedByString:@" "]; 
int index = [words indexOfObject:@"string"]; 

我不知道如果我要像做

NSString*needle=words[index+1]; 

if (needle isEqualto @"") { 
    //There is a word after @"string"; 
} 

我應該怎麼辦?

我怎麼能確定是有後@「串」字?

我感謝所有幫助! :)

回答

-1

方法componentsSeparatedByString:會給通過輸入NSString分開的所有組件。

你如。 NSArray *words = [texfield.text componentsSeparatedByString:@" "];

將不得不" "分隔的所有字符串。所以只是檢查是否有

NSInteger afterIndex = index+1; if(afterIndex<words.count)如果是,你有NSString可用。

0

是的,你必須:

NSArray *words = [texfield.text componentsSeparatedByString:@" "]; 
NSInteger index = [words indexOfObject:@"string"]; 

NSInteger afterIndex = index+1; 
if(afterIndex<words.count) { 
    NSString *needle = words[index+1]; 
    if (needle isEqualToString @"") { 
     //do something 
    } 
} 
0
NSString *yourString = @"string stackoverflow word after string regex"; 
NSRange yourStringRange = NSMakeRange(0, [yourString length]); 
NSString *pattern = @"string\\s*([^\\s]*)"; 
NSError *error = nil; 

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error]; 
NSArray* matches = [regex matchesInString:yourString options:0 range: yourStringRange]; 
for (NSTextCheckingResult* match in matches) { 
    NSRange rangeForMatch = [match rangeAtIndex:1]; 
    NSLog(@"word after STRING: %@", [yourString substringWithRange:rangeForMatch]); 
} 

輸出:

word after STRING: stackoverflow 
word after STRING: regex