Java Android - 如何在 android 中将字符串转换为 utf-8
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31109345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - How to Convert String to utf-8 in android
提问by u5059958
I can't convert a String to UTF-8 in android. please help me!!
我无法在 android 中将字符串转换为 UTF-8。请帮我!!
s1=URLEncoder.encode("臺北市")
result : %EF%BF%BDO%EF%BF%BD_%EF%BF%BD%EF%BF%BD
结果 : %EF%BF%BDO%EF%BF%BD_%EF%BF%BD%EF%BF%BD
But "臺北市
" should be encoded as "%E8%87%BA%E5%8C%97%E5%B8%82
"
但是“ 臺北市
”应该编码为“ %E8%87%BA%E5%8C%97%E5%B8%82
”
采纳答案by sonic
In http://developer.android.com/reference/java/net/URLEncoder.htmlyou can read that the you used is deprecated and that you should use static String encode(String s, String charsetName)
在http://developer.android.com/reference/java/net/URLEncoder.html 中,您可以看到您使用的已弃用,您应该使用static String encode(String s, String charsetName)
So URLEncoder.encode("臺北市", "utf-8")
should do the trick.
所以URLEncoder.encode("臺北市", "utf-8")
应该做的伎俩。
回答by Ahmad Sanie
use this:
用这个:
URLEncoder.encode("臺北市", "UTF-8");
回答by Aritra Roy
You can just use,
你可以使用,
URLEncoder.encode(string, "UTF-8");
This will encode your "string: in UTF-8 format.
这将编码您的“字符串:以 UTF-8 格式。
Put it in a try/catch and check for IllegalArgumentException if you want to. And if you have any spaces in your string, please replace it with
如果需要,请将其放入 try/catch 并检查 IllegalArgumentException。如果您的字符串中有任何空格,请将其替换为
string.replace(" ", "%20");
回答by Paras Santoki
public class StringFormatter {
// convert UTF-8 to internal Java String format
public static String convertUTF8ToString(String s) {
String out = null;
try {
out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
// convert internal Java String format to UTF-8
public static String convertStringToUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
}
You can convert your string using StringFormatter class to your code.
您可以使用 StringFormatter 类将字符串转换为代码。
You want to convert to UTF-8:
您想转换为 UTF-8:
String normal="This normal string".
String utf=StringFormatter.convertStringToUTF8(normal);
You want to convert UTF-8 to normal format:
您想将 UTF-8 转换为普通格式:
String normal=StringFormatter.convertUTF8ToString(normal);