我想得到这些特定字母的百分比编码字符串,如何在objective-c中做到这一点?
Reserved characters after percent-encoding
! * ' ( ) ; : @ & = + $ , / ? # [ ]
%21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D
请使用此字符串进行测试,看看它是否可以工作:
myURL = @"someurl/somecontent"
我希望字符串看起来像这样:
myEncodedURL = @"someurl%2Fsomecontent"
我已经尝试了stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding
,但它不起作用,结果仍然与原始字符串相同。敬请指教。
发布于 2010-08-07 01:20:25
我发现stringByAddingPercentEscapesUsingEncoding:
和CFURLCreateStringByAddingPercentEscapes()
都不够用。NSString
方法遗漏了相当多的字符,而CF函数只允许您说出要转义的(特定)字符。正确的规范是转义除一小部分之外的所有字符。
为了解决这个问题,我创建了一个NSString
类别方法来正确地对字符串进行编码。它将对除[a-zA-Z0-9.-_~]
之外的所有内容进行百分比编码,还会将空格编码为+
(根据this specification的说法)。它还可以正确地处理unicode字符的编码。
- (NSString *) URLEncodedString_ch {
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
发布于 2010-08-06 20:20:50
NSString *encodedString = [myString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
它不会替换你的内联字符串;它会返回一个新的字符串。该方法以单词"string“开头的事实表明了这一点。根据当前的NSString实例化NSString的新实例是一种方便的方法。
注意--新的字符串将是autorelease
'd,所以当你使用完它时,不要对它调用release。
发布于 2016-09-15 00:32:53
遵循RFC3986标准,下面是我用来编码URL组件的代码:
// https://tools.ietf.org/html/rfc3986#section-2.2
let rfc3986Reserved = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?#[]")
let encoded = "email+with+plus@example.com".stringByAddingPercentEncodingWithAllowedCharacters(rfc3986Reserved.invertedSet)
输出:email%2Bwith%2Bplus%40example.com
https://stackoverflow.com/questions/3423545
复制相似问题