Replace the last part of a string

Viewed 108434

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)

11 Answers

On a similar search I found this answer:

Replace Last Occurrence of a character in a string

I think it is the best, because it uses the Java methods as intended rather than trying to reinvent the wheel.

It essentially reads the string backwards and uses the String object's replaceFirst method, this is exactly what I was looking for.

Here is the documentation on replaceFirst String method and the StringBuffer's reverse function:

replaceFirst

reverse

Here is how I implemented it to simply remove some HTML 'pre' tags from a code snippet that I wanted to interpret. Remember to reverse your search string as well, and then reverse everything back to normal afterwards.

private String stripHtmlPreTagsFromCodeSnippet(String snippet) {
    String halfCleanSnippet = snippet.replaceFirst("<pre>", "");
    String reverseSnippet = new StringBuffer(halfCleanSnippet).reverse().toString();
    String reverseSearch = new StringBuffer("</pre>").reverse().toString();
    String reverseCleanSnippet = reverseSnippet.replaceFirst(reverseSearch, "");
    return new StringBuffer(reverseCleanSnippet).reverse().toString();
}
Related