Objective-c iPhone百分比编码字符串? [英] Objective-c iPhone percent encode a string?
问题描述
我想获得这些特定字母的百分比编码字符串,如何在objective-c中做到这一点?
I would like to get the percent encoded string for these specific letters, how to do that in 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
请使用此字符串进行测试,看看它是否有效:
Please test with this string and see if it do work:
myURL = @"someurl/somecontent"
我希望字符串看起来像:
I would like the string to look like:
myEncodedURL = @"someurl%2Fsomecontent"
我已经尝试使用 stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding
但它不起作用,结果仍然与原始字符串相同.请指教.
I tried with the stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding
already but it does not work, the result is still the same as the original string. Please advice.
推荐答案
我发现 stringByAddingPercentEscapesUsingEncoding:
和 CFURLCreateStringByAddingPercentEscapes()
都不够用.NSString
方法遗漏了相当多的字符,而 CF 函数只让您说出要转义的(特定)字符.正确的规范是转义除小集之外的所有字符.
I've found that both stringByAddingPercentEscapesUsingEncoding:
and CFURLCreateStringByAddingPercentEscapes()
are inadequate. The NSString
method misses quite a few characters, and the CF function only lets you say which (specific) characters you want to escape. The proper specification is to escape all characters except a small set.
为了解决这个问题,我创建了一个 NSString
类别方法来正确编码字符串.它将对除 [a-zA-Z0-9.-_~]
之外的所有内容进行百分比编码,并将空格编码为 +
(根据 本规范).它还可以正确处理编码 unicode 字符.
To fix this, I created an NSString
category method to properly encode a string. It will percent encoding everything EXCEPT [a-zA-Z0-9.-_~]
and will also encode spaces as +
(according to this specification). It will also properly handle encoding unicode characters.
- (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;
}
这篇关于Objective-c iPhone百分比编码字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!