在文本字段中的特定字符串之前的textfield中获取字符串

时间:2015-07-14 11:56:39

标签: ios objective-c nsstring

所以我的textfield有以下文字。 @"A big Tomato is red."

我希望在""之前得到这个词。

当我输入

  NSString *someString = [[textfield componentsSeparatedByString:@"is"]objectAtIndex:0];

我总是"A big Tomato"而不是"Tomato"。在应用程序中,人们会在"is"之前输入内容,因此我需要始终在"is"之前获取字符串。我将不胜感激任何帮助。 *警告,

这是一个非常棘手的问题。

3 个答案:

答案 0 :(得分:3)

试试这个,

NSString *value = @"A big Tomato is red.";
NSArray *array = [value componentsSeparatedByString:@" "];
if ([array containsObject:@"is"]) {
    NSInteger index = [array indexOfObject:@"is"];
    if (index != 0) {
        NSString *word = [array objectAtIndex:index - 1];
        NSLog(@"%@", word);
    }
}

答案 1 :(得分:1)

试试这个

 NSString *string = @"A big Tomato is red.";
    if ([string rangeOfString:@"is"].location == NSNotFound) {
      NSLog(@"string does not contain is");
    } else {
      NSLog(@"string contains is!");
    }

希望它有所帮助。

答案 2 :(得分:0)

试试这个

NSString *str = @"A big tomato is red";
NSArray *arr = [str componentsSeparatedByString:@" "];
int index = [arr indexOfObject:@"is"];
if(index > 1)
    NSString *str_tomato = arr[index-1];
else
    //"is" is the first word of sentence

根据yvesleborg的评论

相关问题