Objective-C: Substring and replace

二次信任 提交于 2020-01-05 08:04:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!