【问题标题】:Android replace strings doesnt work [duplicate]Android替换字符串不起作用[重复]
【发布时间】:2017-07-25 02:49:49
【问题描述】:

在下面的字符串数组中我有这个标签:

String[] tags = {
        "<mft:A>",
        "<mft:S>",
        "<mft:R>",
        "</mft:A>",
        "</mft:S>",
        "</mft:R>"
};

我想用这个html标签替换它们:

String[] replacementHtmlTags = {
        "<font color=\"red\">",
        "<font color=\"green\">",
        "<font color=\"blue\">",
        "</font>",
        "</font>",
        "</font>"
};

现在在定义目标和替换后我的代码不起作用:

String rawParagraph = "11111 <mft:A>22222</mft:A> 33333 <mft:S> 44444 <mft:A> 555555 <mft:S> 66666 </mft:S></mft:A></mft:S><mft:R> 77777 </mft:R>"

for (int tag = 0; tag < tags.length; tag++) {
    rawParagraph.replace(tags[tag], replacementHtmlTags[tag]);
}

【问题讨论】:

  • 字符串是不可变的,所以replace()返回新值。它不会(不能)更新当前值。
  • @Andreas 好的,那么我怎样才能像我的代码一样使用数组替换所有标签?
  • @Andreas,谢谢,问题已解决

标签: java android


【解决方案1】:

我认为您应该遵循这种方法以获得更好的可用性和映射:

public static HashMap<String, String> keyVal;

static {
    keyVal = new HashMap<String, String>();
    keyVal.put("<mft:A>", "<font color=\\red\">");
    keyVal.put("<mft:S>", "<font color=\\green\">");
    keyVal.put("<mft:R>", "<font color=\\blue\">");
    keyVal.put("</mft:A>", "</font>");
    keyVal.put("</mft:S>", "</font>");
    keyVal.put("</mft:R>", "</font>");
}

public String replaceTag(String replace) {
    for(String key:keyVal.keySet())
        replace=replace.replaceAll(key,keyVal.get(key));
    return replace;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-07
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多