如何用十六进制值替换ASCII文本

时间:2016-01-27 11:15:39

标签: android hex ascii str-replace

我有一个字符串

msg = "Hello.. welcome. Your ID is 'abcd' & pwd is '123' !!";

我正在用

替换空白区域

msg = msg.replaceAll("\\s+", "%20");

结果是

msg = "Hello..%20welcome.%20Your%20id%20is%20'abcd'%20&%20pwd%20is%20'123'!!

如何替换ASCII文本,如(& ')等十六进制值。

会产生类似

的字符串
msg = "Hello..%20welcome.%20Your%20id%20is%20%27abcd%27%20%26%20pwd%20is%20%27123%27%21%21

2 个答案:

答案 0 :(得分:1)

试试这个课程

public class EncodingDecodingUtil {
    private final static String UTF_8 = "UTF-8";
    private static final String TAG = EncodingDecodingUtil.class.getName();

    /**
     * This method Encode String to UTF -8
     *
     * @param stringToEncode
     * @return return Decoded String Or Same String if exception
     */
    public static String encodeString(String stringToEncode) {
        String encodedString = null;
        Logger.e("before encoding", stringToEncode);
        try {
            encodedString = java.net.URLEncoder.encode(stringToEncode, UTF_8).replace("+", "%20");
            ;
        } catch (Exception e) {
            Logger.e(TAG, "String encoding" + e);
        }

        if (encodedString == null) {
            return stringToEncode;
        }
        Logger.e("after encoding", encodedString);

        return encodedString;
    }


    /**
     * This method decode String from UTF -8
     *
     * @param stringToEncode
     * @return return Decoded String Or Same String if exception
     */
    public static String decodeString(String stringToDecode) {
        String decodedString = null;
        try {
            decodedString = java.net.URLDecoder.decode(stringToDecode, UTF_8);
        } catch (Exception e) {
            Logger.e(TAG, "String decoding" + e);
        }

        if (decodedString == null) {
            return stringToDecode;
        }
        Logger.e("after decoding", decodedString);
        return decodedString;
    }
}

<强>用法

String decodedMsg = EncodingDecodingUtil.decodeString(msg);

String encodedMsg = EncodingDecodingUtil.encodeString(msg);

答案 1 :(得分:0)

试试这个,

String query = URLEncoder.encode(msg, "utf-8").replace("+", "%20");

修改

这是一种更好的方式。

String url = Uri.parse(msg)
                .buildUpon()
                .build()
                .toString();