我尝试使用Objective-c
对url字符串进行编码// 1. Get string
char res = ((char)(400));
NSString *unencodedString = [NSString stringWithFormat:@"%c",res];
// 2. Encode string
static NSString *escape = @":/?&=;+!@#$()',*[]";
NSString *result = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)unencodedString,
NULL,
(__bridge CFStringRef)escape,
kCFStringEncodingUTF8);
// result = %C2%90
但结果不是我所期待的。因为我使用其他编程语言%C6%90
。
如您所见,Objective-C结果为%C2%90
,但我希望%C6%90
。
我的错误在哪里?我做错了吗?
答案 0 :(得分:2)
问题是NSString *unencodedString = [NSString stringWithFormat:@"%c",res]
不符合你的想法。 char res
无法保存大于128的值(unsigned char
为256)。
char res = ((char)(400));
NSString *unencodedString = [NSString stringWithFormat:@"%c",res];
XCTAssertEqualObjects(unencodedString, @"\xc2\x90", @"");
static NSString *escape = @":/?&=;+!@#$()',*[]";
NSString *result = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)unencodedString,
NULL,
(__bridge CFStringRef)escape,
kCFStringEncodingUTF8);
XCTAssertEqualObjects(result, @"%C2%90", @"");
这是一个有效的例子。
NSString *unencodedString = @"Ɛ";
static NSString *escape = @":/?&=;+!@#$()',*[]";
NSString *result = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)unencodedString,
NULL,
(__bridge CFStringRef)escape,
kCFStringEncodingUTF8);
XCTAssertEqualObjects(result, @"%C6%90", @"");
<强>更新强>
如果您希望此类示例有效,请使用unichar
和-stringWithCharacters:length:
。
unichar res = ((unichar)(400));
NSString *unencodedString = [NSString stringWithCharacters:&res length:1];
XCTAssertEqualObjects(unencodedString, @"Ɛ", @"");
static NSString *escape = @":/?&=;+!@#$()',*[]";
NSString *result = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)unencodedString,
NULL,
(__bridge CFStringRef)escape,
kCFStringEncodingUTF8);
XCTAssertEqualObjects(result, @"%C6%90", @"");