【问题标题】:Replace Last Occurrence of a character in a string [duplicate]替换字符串中最后一次出现的字符[重复]
【发布时间】:2013-05-15 22:44:42
【问题描述】:

我有这样的字符串

"Position, fix, dial"

我想用转义双引号(\")替换最后一个双引号(")

字符串的结果是

"Position, fix, dial\"

我该怎么做。我知道替换第一次出现的字符串。但不知道如何替换最后出现的字符串

【问题讨论】:

    标签: java string replace last-occurrence


    【解决方案1】:
    String str = "\"Position, fix, dial\"";
    int ind = str.lastIndexOf("\"");
    if( ind>=0 )
        str = new StringBuilder(str).replace(ind, ind+1,"\\\"").toString();
    System.out.println(str);
    

    更新

     if( ind>=0 )
        str = new StringBuilder(str.length()+1)
                    .append(str, 0, ind)
                    .append('\\')
                    .append(str, ind, str.length())
                    .toString();
    

    【讨论】:

    • 只是问。为什么不这样? String str = "\"Position, fix, dial\""; str.replaceAll("[\"]\\Z", "\""); System.out.println(str);
    • 是的,您可以使用 str = str.replaceAll("[\"]\\Z", "\\\\\"") 之类的东西。但它将替换输入末尾的最后一个引号。对于“定位、修复、拨号”再次不起作用 >.
    • @Dudeist 因为这样可读性差很多。
    【解决方案2】:
    String docId = "918e07,454f_id,did";
    StringBuffer buffer = new StringBuffer(docId);
    docId = buffer.reverse().toString().replaceFirst(",",";");
    docId = new StringBuffer(docId).reverse().toString();
    

    【讨论】:

    • 这仅适用于单个字符的东西。
    【解决方案3】:

    如果您只想删除 las 字符(如果有的话),这是一种单行方法。我将它用于目录。

    localDir = (dir.endsWith("/")) ? dir.substring(0,dir.lastIndexOf("/")) : dir;
    

    【讨论】:

      【解决方案4】:

      这应该可行:

      String replaceLast(String string, String substring, String replacement)
      {
        int index = string.lastIndexOf(substring);
        if (index == -1)
          return string;
        return string.substring(0, index) + replacement
                + string.substring(index+substring.length());
      }
      

      这个:

      System.out.println(replaceLast("\"Position, fix, dial\"", "\"", "\\\""));
      

      打印:

      "Position, fix, dial\"
      

      Test.

      【讨论】:

      • 这比公认的答案要好,因为它是通用的。
      猜你喜欢
      • 2014-06-13
      • 2011-04-19
      • 2012-12-01
      • 2011-07-26
      • 2018-01-18
      • 1970-01-01
      • 2016-02-14
      相关资源
      最近更新 更多