Reputation: 2329
In objective c how to Remove text after a string occurrence.
for example i have to remove a text after occurrence of text 'good'
'iphone is good but..' here i have to remove the but text in the end so the text will be now 'iphone is good'
Upvotes: 0
Views: 1199
Reputation: 7986
If you want to remove rest of the string after a particular occurrence of "but", you can get the range of "but" and trim the original string down
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 We can assume that the search does not want to cut of "butter is yellow", and can change the range to include " but"
NSRange range = [test rangeOfString:@" but"];
Upvotes: 1
Reputation: 43
NSArray *array = [string componentsSeparatedByString:stringToSearch];
NSString *requiredString;
if ([array count] > 0) {
requiredString = [[array objectAtIndex:0] stringByAppendingString:stringToSearch];
}
Upvotes: 0
Reputation: 6323
Try with below code
NSString *str_good = @"iphone is good but...";
NSRange range = [str_good rangeOfString:@"good"];
str_good = [str_good substringToIndex:range.location+range.length];
Upvotes: 4
Reputation: 4732
NSString * a = @"iphone is good but..";
NSRange match = [a rangeOfString:@"good"];
NSString * b = [a substringToIndex:match.location+match.length];
Upvotes: 3
Reputation: 2676
Try this:-
NSArray *array = [string componentsSeperatedBy:@"good"];
NSString *requiredString = [array objectAtIndex:0];
Upvotes: 0