Replace the last part of a string

JavaRegexStringReplace

Java Problem Overview


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)

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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

Solution 5 - Java

Use Apache Commons' StringUtils function removeEnd():

StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"

Solution 6 - Java

The more readable way ... Which you can use to learn about String and its functions

String myString = "Insert into dual (name,date,";
String newString = "";
int length = myString.length();
String lastChar = myString.substring(length-1);

if (lastChar.contains(",")) {
    newString = myString.substring(0,length-1) + ")";
}

System.out.println(newString);

Solution 7 - Java

Check the length of the string, check the last character (if you have the length it is easy), and replace it - when necessary.

This solution is not language-specific - just use common sense.

Solution 8 - Java

On a similar search I found this answer:

https://stackoverflow.com/questions/16665387/replace-last-occurrence-of-a-character-in-a-string/37066403#37066403

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

Solution 9 - Java

Try this regex (^.+)b(.+$)

Example (Replace the last b character)

System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", "$1$2"));

Solution 10 - Java

To replace the last character of your string by ):

str = str.substring(0, str.length()-1)+")";

Make sure your string is not empty or null.

Solution 11 - Java

What’s up with the hassle if you can just do the following?

word = (String) word.subSequence(0, word.length() -1);

This returns a new String without the last part of a String.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarishView Question on Stackoverflow
Solution 1 - JavajjnguyView Answer on Stackoverflow
Solution 2 - JavaNawaManView Answer on Stackoverflow
Solution 3 - JavaIvan CadernoView Answer on Stackoverflow
Solution 4 - JavasfusseneggerView Answer on Stackoverflow
Solution 5 - JavaPhilipView Answer on Stackoverflow
Solution 6 - Javaty812View Answer on Stackoverflow
Solution 7 - JavaDaniView Answer on Stackoverflow
Solution 8 - JavamatttrachView Answer on Stackoverflow
Solution 9 - JavaMuhammad GelbanaView Answer on Stackoverflow
Solution 10 - JavaSe SongView Answer on Stackoverflow
Solution 11 - JavaralphgabbView Answer on Stackoverflow