Search code examples
objective-creplacensstringsubstringnsrange

Objective-C: Substring and replace


I have a NSString which is a URL. This URL need to be cut:

NSString *myURL = @"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByReplacingCharactersInRange:[myURL rangeOfString:@"/" options:NSBackwardsSearch] withString:@""];

I have this URL http://www.test.com/folder/testfolder and I want that the test variable should have the value http://www.test.com/folder/, so the testfolder should be cut. So I tried to find the NSRange testfolder to replace it with an empty string.

But it does not work. What I am doing wrong?


Solution

  • You can turn it into a URL and use -[NSURL URLByDeletingLastPathComponent]:

    NSString *myURLString = @"http://www.test.com/folder/testfolder";
    NSURL *myURL = [NSURL URLWithString:myURLString];
    myURL = [myURL URLByDeletingLastPathComponent];
    myURLString = [myURL absoluteString];