如何剪裁到NSString中的URL?

时间:2014-05-16 19:22:14

标签: ios objective-c replace nsstring

我在调试时以这种方式得到了我的网址:

myURL   __NSCFString *  @"(\n    "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png"\n)"  0x0a8a3510

我尝试通过方法

(\n\n)替换为""
tringByReplacingOccurrencesOfString:@" (\n " withString:@""

最后我以这种方式得到了我的网址

myURL   __NSCFString *  @"   "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png"" 0x08c12540

但我想要的是

myURL   __NSCFString *  @"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png"  0x08c12540

有没有什么好方法可以帮助我获得我想要的字符串?

1 个答案:

答案 0 :(得分:0)

这应该修剪字符串末尾的非URL字符,加上括号字符:

NSMutableCharacterSet* urlSet = [[NSMutableCharacterSet alloc] init];
urlSet = [urlSet formUnionWithCharacterSet:[NSCharacterSet URLUserAllowedCharacterSet]];
urlSet = [urlSet formUnionWithCharacterSet:[NSCharacterSet URLPasswordAllowedCharacterSet]];
urlSet = [urlSet formUnionWithCharacterSet:[NSCharacterSet URLHostAllowedCharacterSet]];
urlSet = [urlSet formUnionWithCharacterSet:[NSCharacterSet URLPathAllowedCharacterSet]];
urlSet = [urlSet formUnionWithCharacterSet:[NSCharacterSet URLQueryAllowedCharacterSet]];
urlSet = [urlSet formUnionWithCharacterSet:[NSCharacterSet URLFragmentAllowedCharacterSet]];
urlSet = [[urlSet invertedSet] mutableCopy];
[urlSet addCharactersInString:@"()"];

myURL = [myURL stringByTrimmingCharactersInSet:urlSet];

如果它实际上是反斜杠+ n而不是换行符,则在剥离“\ n”之后可能需要这样做。