【问题标题】:How to replace ASCII Text with Hex Value如何用十六进制值替换 ASCII 文本
【发布时间】:2016-05-04 07:29:53
【问题描述】:

我有一个字符串

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

【问题讨论】:

  • 嘿,看看我的答案,告诉我它是否解决了你的问题

标签: android hex ascii str-replace


【解决方案1】:

试试这个,

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

编辑

这是一个更好的方法。

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

【讨论】:

  • 日志:query﹕ Hello..+welcome.+Your+ID+is+%27abcd%27+%26+pwd+is+%27123%27+%21%21 空格未被替换
  • @KNeerajLal 这会添加一个新行吗?我的意思是\n
【解决方案2】:

试试这个课程

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);

【讨论】:

  • OMG.. O.O 没想到字符串替换可能需要 1 类 2 方法
  • @Prabs 我建议这样做,以便您可以将其用作实用程序类
  • 对不起@Harsh,但我真的很懒惰尝试实用程序类,并且在执行这些类和方法来替换字符串时利用处理器时间可能不是一个好习惯。你认为这是一个更好的选择吗?
  • @Prabs 当且仅当您的项目在很多地方都需要这种任务(编码解码)时会更好
  • 我尊重您为解决问题所做的努力。我更喜欢接受的答案
猜你喜欢
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 2012-11-14
  • 2016-09-27
  • 1970-01-01
  • 2018-12-06
相关资源
最近更新 更多