将字符串转换为UTF8

时间:2016-07-25 06:20:12

标签: ios objective-c utf-8

如何将NSString转换为UTF8Encode?

我的NSLog打印与输入字符串相同的结果

    NSString*  username =@"MYUSERNAME";
    username=[username stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString*  Password =@"MYUSERNAMEPASS";
    Password=[Password stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"username=%@",username);
    NSLog(@"Password=%@",Password);

1 个答案:

答案 0 :(得分:3)

您需要使用stringByAddingPercentEscapesUsingEncoding代替stringByReplacingPercentEscapesUsingEncoding

NSString *encodeUserName = [username stringByAddingPercentEscapesUsingEncoding:NSUTF32StringEncoding];

此外,stringByAddingPercentEscapesUsingEncoding也已弃用,因此请使用stringByAddingPercentEncodingWithAllowedCharacters这样的

NSString *encodeUserName = [username stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];