【问题标题】:Issues with replacing ' " ' in a string在字符串中替换 '"' 的问题
【发布时间】:2012-12-27 21:33:07
【问题描述】:

我正在尝试从包含引号中的文本 "matchup" 的字符串中删除子字符串。要删除的完整子字符串类似于To get an in-depth statistical preview, click "matchup" at the top of the screen

我正在尝试做一个

string.replace("To get an in-depth statistical preview, click "matchup" at the top of the screen", "");

这会将那个长句子替换为空白;然而,由于“matchup”在字符串中实际上有引号,当我将它作为参数传入时,它会吓坏并认为我有两个单独的字符串,它们之间有一些随机的文本matchup

对不起,如果这很难理解,我可能做得不好。我也试过做

...'matchup'.... rather than ..."matchup"... 

它似乎不起作用。

【问题讨论】:

  • 转义“这样的\”
  • 如果这是 Java 代码,您的示例甚至无法编译。你确定java 标签在这里合适吗?

标签: java string replace


【解决方案1】:

您可以使用\" 在字符串中表示"

所以

string.replace("To get an in-depth statistical preview, click \"matchup\" at the top of the screen", "")

【讨论】:

    【解决方案2】:

    添加一些分隔符,即string.replace(" my \"string\" ", " ")

    【讨论】:

      【解决方案3】:

      某些字符需要在字符串文字(甚至字符文字)中转义,如 Java 中的 here 所述。

      你应该用\"来代表"

      【讨论】:

        【解决方案4】:

        我正在尝试删除包含以下文本的字符串

        “对决”

        string.replace("\"matchup\"", "")
        

        【讨论】:

          【解决方案5】:

          您需要使用\" 将引号转义为

          String newString = string.replace("To get an in-depth statistical preview, click \"matchup\" at the top of the screen", "");
          

          由于字符串是不可变的,replace 不能在原地工作,您需要将string.replace(..., ...) 的结果分配给新字符串。

          【讨论】:

            【解决方案6】:

            简单的方法是使用\" 显示"

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-11-08
              • 2010-10-04
              • 2015-10-11
              • 2011-11-24
              • 1970-01-01
              • 1970-01-01
              • 2020-03-15
              • 1970-01-01
              相关资源
              最近更新 更多