首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Objective-c iPhone percent编码字符串?

Objective-c iPhone percent编码字符串?
EN

Stack Overflow用户
提问于 2010-08-06 20:02:47
回答 6查看 49.7K关注 0票数 72

我想得到这些特定字母的百分比编码字符串,如何在objective-c中做到这一点?

代码语言:javascript
复制
Reserved characters after percent-encoding
!   *   '   (   )   ;   :   @   &   =   +   $   ,   /   ?   #   [   ]
%21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D

Percent-encoding wiki

请使用此字符串进行测试,看看它是否可以工作:

代码语言:javascript
复制
myURL = @"someurl/somecontent"

我希望字符串看起来像这样:

代码语言:javascript
复制
myEncodedURL = @"someurl%2Fsomecontent"

我已经尝试了stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding,但它不起作用,结果仍然与原始字符串相同。敬请指教。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-08-07 01:20:25

我发现stringByAddingPercentEscapesUsingEncoding:CFURLCreateStringByAddingPercentEscapes()都不够用。NSString方法遗漏了相当多的字符,而CF函数只允许您说出要转义的(特定)字符。正确的规范是转义除一小部分之外的所有字符。

为了解决这个问题,我创建了一个NSString类别方法来正确地对字符串进行编码。它将对除[a-zA-Z0-9.-_~]之外的所有内容进行百分比编码,还会将空格编码为+ (根据this specification的说法)。它还可以正确地处理unicode字符的编码。

代码语言:javascript
复制
- (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;
}
票数 144
EN

Stack Overflow用户

发布于 2010-08-06 20:20:50

代码语言:javascript
复制
NSString *encodedString = [myString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

它不会替换你的内联字符串;它会返回一个新的字符串。该方法以单词"string“开头的事实表明了这一点。根据当前的NSString实例化NSString的新实例是一种方便的方法。

注意--新的字符串将是autorelease'd,所以当你使用完它时,不要对它调用release。

票数 5
EN

Stack Overflow用户

发布于 2016-09-15 00:32:53

遵循RFC3986标准,下面是我用来编码URL组件的代码:

代码语言:javascript
复制
// 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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3423545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档