iphone删除下一个字符串 - 在特殊字符串出现后留下其余的字符串

时间:2011-11-30 05:01:37

标签: iphone objective-c ios nsstring

在目标c中如何在字符串出现后删除文本。

例如,我必须在文本'good'

出现后删除文本

'iphone很好,但是......'在这里我必须删除文本到底,所以文字现在是'iphone很好'

5 个答案:

答案 0 :(得分:4)

  

尝试使用以下代码

NSString *str_good = @"iphone is good but...";
NSRange range = [str_good rangeOfString:@"good"];
str_good = [str_good substringToIndex:range.location+range.length];

答案 1 :(得分:3)

NSString * a = @"iphone is good but..";
NSRange match = [a rangeOfString:@"good"];
NSString * b = [a substringToIndex:match.location+match.length];

答案 2 :(得分:1)

如果你想在特定的“but”之后删除其余的字符串,你可以获得“but”的范围并修剪原始字符串

NSString * test = [NSString stringWithString:@"iphone is good but rest of string"];
NSRange range = [test rangeOfString:@"but"];
if (range.length > 0)   {
    NSString *adjusted = [test substringToIndex:range.location];
    NSLog(@"result %@", adjusted);
}

EDIT 我们可以假设搜索不想削减“黄油是黄色”,并且可以改变范围以包括“但是”

NSRange range = [test rangeOfString:@" but"];

答案 3 :(得分:0)

试试这个: -

  NSArray *array = [string componentsSeperatedBy:@"good"];
  NSString *requiredString = [array objectAtIndex:0];

答案 4 :(得分:0)

NSArray *array = [string componentsSeparatedByString:stringToSearch];
NSString *requiredString;
if ([array count] > 0) {
    requiredString = [[array objectAtIndex:0] stringByAppendingString:stringToSearch];
}