【问题标题】:Replace all td's tags by th in a java String在 java 字符串中用 th 替换所有 td 的标签
【发布时间】:2017-12-11 13:20:33
【问题描述】:

我想把这个字符串中的所有“td”替换为“th”

String head = "<tr>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td>Libelle</td>\n" 
                      + "<td>Nom Table</td>\n<td>Groupe</td>\n<td>&nbsp;</td>\n</tr>\n"

我尝试使用:

head.replace("<td>", "<th>");
head.replace("</td>", "</th>");

但它不起作用。

你能帮帮我吗?

【问题讨论】:

  • 使用 replaceAll()
  • 使用head.replaceAll("td", "th");你甚至不需要单独指定开始/结束标签,除非你在你的字符串中除了标签之外的其他地方有td
  • @Abubakkar 省略&lt;&gt; 可能是个坏主意,因为它会替换诸如outdoor 之类的单词中的td

标签: java


【解决方案1】:

String.replace(..) 将返回结果字符串,因此您需要将其设置回来

head = head.replace("<td>", "<th>");
head = head.replace("</td>", "</th>");

【讨论】:

  • 您可能想使用head.replaceAll("&lt;td\\b", "&lt;th");,以便处理带有属性的td标签。
【解决方案2】:

在这种情况下,您可以使用replace 方法和replaceAll,因为您没有使用任何正则表达式并且您不能进行嵌套修改(例如"aaa".replace("a","b"))。

而且,修改后的String是由方法返回的(而不是隐式修改),所以应该重新赋值head值。

所以,解决方案应该是这样的:

String head = "<tr>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td>Libelle</td>\n<td>Nom Table</td>\n<td>Groupe</td>\n<td>&nbsp;</td>\n</tr>\n";

head = head.replaceAll("<td>", "<th>");
head = head.replaceAll("</td>", "</th>");

System.out.println(head);

EDIT1:

如果您愿意只修改这些标签(并且始终相同),您可以使用replace method。否则,您应该使用replaceAll 方法,因为它可以包含正则表达式。您可以在Difference between String replace() and replaceAll() 中找到有关replacereplaceAll 之间区别的更多信息

【讨论】:

  • head = head.replaceAll("td", "th");就够了
  • @abc123 但会冒着替换单词片段的风险,例如将outdoor转换为outhoor
  • @Aaron 那么这个 head = head.replaceAll("td>", "th>");
  • 我发现 replace 确实会修改所有外观,所以我猜想这两种方法有什么区别。查看更新的答案
  • @abc123 我真的不知道省略 ) 将只安全地删除您需要的条目,而无需担心极端情况。如果我们可以将比较简化为只有一个字符,我承认它可以带来性能优势。不然我觉得没用
【解决方案3】:

你可以这样写一行。

 head = head.replaceAll("td>", "th>");

【讨论】:

    【解决方案4】:

    这可以处理空 &lt;td /&gt;&lt;td/&gt; 标签等场景以及当您的 td 标签具有 class=\"abc\" 之类的属性时:

    String head  = ""<td class=\"abc\">outdoor</td><td />"";
    head = head.replace("<td", "<th");
    head = head.replace("</td", "</th");
    System.out.println(head);
    

    【讨论】:

      【解决方案5】:

      replace 方法返回一个新字符串。

      字符串 s="hi hi hi";

      String f= s.replace("hi", "bye");

      System.out.println(s+ "----" + f);

      打印:hi hi hi----bye bye bye

      【讨论】:

        猜你喜欢
        • 2011-06-09
        • 1970-01-01
        • 2013-12-31
        • 2020-01-27
        • 1970-01-01
        • 2012-09-05
        • 1970-01-01
        • 2020-12-04
        • 1970-01-01
        相关资源
        最近更新 更多