Replace the last part of a string

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)


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).