Replace the last part of a string

106,369

Solution 1

The following code should replace the last occurrence of a ',' with a ')'.

StringBuilder b = new StringBuilder(yourString);
b.replace(yourString.lastIndexOf(","), yourString.lastIndexOf(",") + 1, ")" );
yourString = b.toString();

Note This will throw Exceptions if the String doesn't contain a ','.

Solution 2

You can use a regular expression:

String aResult = "Insert into dual (name,date,".replaceAll(",$", ")");

replaceAll(...) will match the string with the given regular expression (parameter 1) (in this case we match the last character if it is a comma). Then replace it with a replacement (parameter 2) (in this case is ')').

Plus! If you want to ensure that trailing spaces and tabs are taken care of, you can just change the regular expression to ',\[ \t\]*$'. Note: '\[' and '\]' is without backslash (I don't know how to properly escape it).

Solution 3

This is a custom method to replace only the last substring of a given string. It would be useful for you:

private String replaceLast(String string, String from, String to) {
    int lastIndex = string.lastIndexOf(from);
    if (lastIndex < 0)
        return string;
    String tail = string.substring(lastIndex).replaceFirst(from, to);
    return string.substring(0, lastIndex) + tail;
}

Solution 4

str = str.substring(0, str.lastIndexOf(",")) + ")";

Solution 5

Use Apache Commons' StringUtils function removeEnd():

StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
Share:
106,369
Harish
Author by

Harish

Updated on July 09, 2022

Comments

  • Harish
    Harish almost 2 years

    I want to replace the last String which is a , with ).

    Suppose the string is:

    Insert into dual (name,date,

    It is to be converted to:

    Insert into dual (name,date)

    • matbrgz
      matbrgz over 14 years
      Have you considered rewriting your loop so the right amount of commas show up? I've seen a Stackoverflow question for getting exactly that loop as efficient as possible.
    • dragon66
      dragon66 almost 12 years
      Simply use: "Insert into dual (name,date,".replaceAll(",(?!.*,)",")");
  • Dani
    Dani over 14 years
    I think he tagged it as java, isn't stringbuilder a dotnet ?
  • jjnguy
    jjnguy over 14 years
    Both languages have StringBuilder
  • jjnguy
    jjnguy over 14 years
    Its not the last character, its the last occurrence of a specific character.
  • Dani
    Dani over 14 years
    10x, didn't know that. I think that your solution will replace any last , and not only if it's in the end of the string.
  • jjnguy
    jjnguy over 14 years
    Yeah, my solution will replace the last occurrence of a string even if it isn't the exact last character.
  • Dani
    Dani over 14 years
    Well, the question isn't clear about that. "the last string.." I wonder what he meant...
  • jjnguy
    jjnguy over 14 years
    True, that's why I went for the method that would work in both cases.
  • Esko
    Esko over 14 years
    Dani: StringBuilder in Java is the non-thread safe variant of StringBuffer which makes it noticeably faster (if I remember correctly, about 20-30%) and should be preferred if the thread safe StringBuffer isn't explicitly needed.
  • ty812
    ty812 over 14 years
    That would change the last ",", indiscriminate if it is the last character in a String or not.
  • sfussenegger
    sfussenegger over 14 years
    It works wherever ',' is located - it will ignore anything that follows the last ',' though.
  • mpen
    mpen about 13 years
    heh... thats sick. i thought that was C# at first. only difference is the capitalization of the methods, really.
  • jjnguy
    jjnguy about 13 years
    @Mark, yup. They are very very similar.
  • csonuryilmaz
    csonuryilmaz almost 11 years
    If you use replaceAll(",$", ")") as replaceAll("[,]*$", ")") , it will work although it has several commas. For ex; " (name, date,,," --> " (name, date)". I think this is more flexible.
  • ADTC
    ADTC almost 10 years
    An exception will be thrown by substring if lastIndexOf returns -1.
  • hephestos
    hephestos over 8 years
    using a regex is quicker