Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't convert a String to UTF-8 in android. please help me!!

s1=URLEncoder.encode("臺北市")

result : %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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
116 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

You want to convert to UTF-8:

String normal="This normal string".
String utf=StringFormatter.convertStringToUTF8(normal);

You want to convert UTF-8 to normal format:

String normal=StringFormatter.convertUTF8ToString(normal);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...