Replace last part of string

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 ','.


You can use regular expression:

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

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

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

Hope this helps.


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;
}