将NSString转换成UTF8编码的NSString

1.转换函数转换:

NSString *urlString  = [NSString stringWithFormat:@"http://www.baidu.com"];
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);
NSURL *url = [NSURL URLWithString:encodedString];

2.通过 C 的字符串来转换

NSString *utf8String = @"http://www.baidu.com";
NSString *unicodeStr = [NSString stringWithCString:[utf8String UTF8String] encoding:NSUnicodeStringEncoding];

3.NSURL 中的转换
有时候获取的url中的中文等字符是乱码,网页内容也是乱码,需要进行一下转码才能正确识别NSString,可以用下面的方法
编码:

  • (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc

解码:

  • (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc
// 1.创建 NSURL 对象
// (1)获取 urlString
NSString *urlString = [NSString stringWithFormat:@"http://www.baidu.com"];
(2)编码转换
// NSString *newStr = [urlString stringByReplacingEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *newStr = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url  = [NSURL URLWithString:newStr];
// 2.创建 NSURLRequest 请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];

4.以上两种方法9.0中已经弃用了,可以使用以下的方法来代替
编码

  • (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet)allowedCharacters
    NS_AVAILBLE(10_9,7_0);

解码

  • @property(nullable,readonly,copy)NSString *stringByRemovingPercentEncoding NS_AVAILABLE(10_9,7_0);
NSString *urlString = [NSString stringWithFormat:@"http://www.baidu.com"];
// 编码转换
NSString *newStr = ursString.stringByRemovingPercentEncoding;
NSURL *url = [NSURL URLWithString:newStr];
// 创建 NSURLRequest 请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];

你可能感兴趣的:(将NSString转换成UTF8编码的NSString)