Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 870
Harish Avatar asked Nov 02 '09 08:11

Harish


People also ask

How do you replace a specific part of a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

How do you change the last element of a string in Python?

To replace only the last character in a string, we will pass the regex pattern “. $” and replacement character in sub() function. This regex pattern will match only the last character in the string and that will be replaced by the given character.

How do I change the last occurrence of a string in Java?

Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);

How do you replace a part of a string in Java?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).


3 Answers

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

like image 167
jjnguy Avatar answered Oct 02 '22 13:10

jjnguy


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

like image 23
NawaMan Avatar answered Oct 02 '22 13:10

NawaMan


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;
}
like image 24
Ivan Caderno Avatar answered Oct 02 '22 14:10

Ivan Caderno