2016-07-25 309 views
-1

如何將NSString轉換爲UTF8Encode?將字符串轉換爲UTF8

我的NSLog打印相同的結果,輸入字符串

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

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

添加特殊字符「%20」或一些類似這樣的,並再次檢查。 –

+0

是否要在字符串中添加%或者是否要從字符串中移除%? – user3182143

回答

3

您需要使用stringByAddingPercentEscapesUsingEncoding,而不是stringByReplacingPercentEscapesUsingEncoding

NSString *encodeUserName = [username stringByAddingPercentEscapesUsingEncoding:NSUTF32StringEncoding]; 

而且stringByAddingPercentEscapesUsingEncoding不贊成這樣連擊使用stringByAddingPercentEncodingWithAllowedCharacters這樣

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