55

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)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harish
  • 1,617
  • 4
  • 21
  • 20

11 Answers11

84

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • I think he tagged it as java, isn't stringbuilder a dotnet ? – Dani Nov 02 '09 at 08:39
  • 13
    Both languages have StringBuilder – jjnguy Nov 02 '09 at 08:39
  • 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. – Dani Nov 02 '09 at 08:41
  • Yeah, my solution will replace the last occurrence of a string even if it isn't the exact last character. – jjnguy Nov 02 '09 at 08:42
  • 2
    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. – Esko Nov 02 '09 at 10:05
  • 1
    heh... thats sick. i thought that was C# at first. only difference is the capitalization of the methods, really. – mpen Mar 10 '11 at 02:47
  • @Mark, yup. They are very very similar. – jjnguy Mar 10 '11 at 03:20
  • using a regex is quicker – hephestos Feb 02 '16 at 09:36
41

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
NawaMan
  • 25,129
  • 10
  • 51
  • 77
  • 3
    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. – csonuryilmaz Jul 23 '13 at 16:01
20

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ivan Caderno
  • 201
  • 2
  • 2
9
str = str.substring(0, str.lastIndexOf(",")) + ")";
sfussenegger
  • 35,575
  • 15
  • 95
  • 119
9

Use Apache Commons' StringUtils function removeEnd():

StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Philip
  • 23,316
  • 2
  • 31
  • 31
2

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ty812
  • 3,293
  • 19
  • 36
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dani
  • 14,639
  • 11
  • 62
  • 110
1

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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
matttrach
  • 125
  • 1
  • 6
0

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

Example (Replace the last b character)

System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", "$1$2"));
Muhammad Gelbana
  • 3,890
  • 3
  • 43
  • 81
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Se Song
  • 1,613
  • 2
  • 19
  • 32
-2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ralphgabb
  • 10,298
  • 3
  • 47
  • 56