ObjC:如何将组件从A/B插入到A// B之间?

hzx*_*zxu 2 iphone url objective-c nsstring ios

我需要以这种方式操作一些URL来添加组件:

/img/david/PlayBasketball.jpg

会变成:

/img/HiRes/david/PlayBasketball.jpg

在Objective C for iPhone中,我该怎么做?

提前致谢!

cho*_*own 5

使用NSString方法pathComponentspathWithComponents:

NSString *p = @"/img/david/PlayBasketball.jpg";

NSMutableArray *cmps = [NSMutableArray arrayWitharray:[p pathComponents]];
// cmps will be: ["/", "img", "david", "PlayBasketball.jpg"]

[cmps insertObject:@"HIRes" atIndex:2];
// You want index 2 because "/" is at index 0, and "img" is at index 1.

NSString *newPath = [NSString pathWithComponents:cmps];
// The pathWithComponents method will add the rest of the "/"'s for you
Run Code Online (Sandbox Code Playgroud)

现在,newPath将:@"/img/HiRes/david/PlayBasketball.jpg".