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?

Till
  • 27,559
  • 13
  • 88
  • 122
Tim
  • 13,228
  • 36
  • 108
  • 159

3 Answers3

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/

nacho4d
  • 43,720
  • 45
  • 157
  • 240
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];
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • With this version, the ending slash is still there, instead of the solution to do it with `stringByDeletingLastPathComponent`. – Tim Nov 22 '11 at 10:26
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:@""];
jptsetung
  • 9,064
  • 3
  • 43
  • 55