1

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?

3 Answers 3

3

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];
Sign up to request clarification or add additional context in comments.

1 Comment

With this version, the ending slash is still there, instead of the solution to do it with stringByDeletingLastPathComponent.
3

Try this:

NSString *myURL = @"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByDeletingLastPathComponent];
NSLog(@"%@", test);

you should get > http://www.test.com/folder/

Comments

0

You can't use the NSRange returned by [myURL rangeOfString:@"/" options:NSBackwardsSearch] because its length is "1". So to keep with your idea to use NSRange (other replies using stringByDeletingLastPathComponent seems to be very valid too), here is how you could do it :

NSRange *range=[myURL rangeOfString:@"/" options:NSBackwardsSearch];
NSString *test = [myURL stringByReplacingCharactersInRange:NSMakeRange(range.location,test.length-range.location) withString:@""];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.