以下代码有效,但它很难看并创建了一堆自动释放的对象。我也使用类似的代码来解析保留的HTML字符(用于引号和符号等)。我只是想知道......有更清洁的方式吗?
NSString *result = [[NSString alloc] initWithString:userInput];
NSString *result2 = [result stringByReplacingOccurrencesOfString:@"#"
withString:@"\%23"];
NSString *result3 = [result2 stringByReplacingOccurrencesOfString:@" "
withString:@"\%20"];
formatted = [[result3 stringByReplacingOccurrencesOfString:@"&"
withString:@"\%26"] retain];
[result release];
答案 0 :(得分:1)
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8 );
答案 1 :(得分:0)
您是否尝试过使用stringByAddingPercentEscapesUsingEncoding方法?
formatted = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];