iphone remove next string - leave rest of string after particular occurrence of string

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'


Try this:-

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

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

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

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"];

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

Need Your Help

Running NSURLSession completion handler on main thread

ios multithreading cocoa ios7

I am using a NSURLSession to get the values to populate a TableView. I am updating the TableView in the completion handler, but using [[NSThread currentThread] isMainThread] has shown me that the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.