【问题标题】:String replace function not working in android字符串替换功能在android中不起作用
【发布时间】:2015-08-22 18:33:30
【问题描述】:

我使用以下代码替换了“\”的出现,但它不起作用。

msg="\uD83D\uDE0A";
msg=msg.replace("\\", "|");

我在 Google 上花了很多时间。但没有找到任何解决方案。

也试过了

msg="\uD83D\uDE0A";
msg=msg.replace("\", "|");

【问题讨论】:

  • msg="\uD83D\uDE0A"; 实际上不包含任何反斜杠。 \u#### 被编译成 unicode character
  • 是的,它是笑脸的 unicode。但是问题中提到的有什么选择吗?
  • 你实际上想做什么 - 用竖线字符或其他东西替换笑脸?
  • @MickMnemonic 我想将笑脸的 unicode 发送到我的网址,但是当它到达那里时它丢失了 \。这就是为什么我试图用 | 来改变它。
  • 如果您无法控制输入,则必须在替换之前取回原始字符串。stackoverflow.com/questions/13700333/…

标签: java android


【解决方案1】:

定义的msg 字符串也必须使用这样的转义字符:

msg="\\uD83D\\uDE0A";
msg=msg.replace("\\", "|");

该代码将起作用,它将导致:|uD83D|uDE0A

【讨论】:

【解决方案2】:

如果你想显示一个 unicode 字符的 unicode 整数值,你可以这样做:

String.format("\\u%04X", ch);

(如果您愿意,也可以使用"|" 而不是"\\")。

如果你想要的话,你可以遍历字符串中的每个字符并将其转换为像 "|u####" 这样的文字字符串。

【讨论】:

    【解决方案3】:

    据我了解,您想要获取字符串的 unicode 表示形式。为此,您可以使用来自here 的答案。

    private static String escapeNonAscii(String str) {
    
      StringBuilder retStr = new StringBuilder();
      for(int i=0; i<str.length(); i++) {
        int cp = Character.codePointAt(str, i);
        int charCount = Character.charCount(cp);
        if (charCount > 1) {
          i += charCount - 1; // 2.
          if (i >= str.length()) {
            throw new IllegalArgumentException("truncated unexpectedly");
          }
        }
    
        if (cp < 128) {
          retStr.appendCodePoint(cp);
        } else {
          retStr.append(String.format("\\u%x", cp));
        }
      }
      return retStr.toString();
    }
    

    这会将 unicode 值作为字符串提供给您,然后您可以随意替换。

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 2021-07-04
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 2020-09-23
      相关资源
      最近更新 更多