问题
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?
回答1:
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];
回答2:
Try this:
NSString *myURL = @"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByDeletingLastPathComponent];
NSLog(@"%@", test);
you should get > http://www.test.com/folder/
回答3:
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:@""];
来源:https://stackoverflow.com/questions/8214193/objective-c-substring-and-replace