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)
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.
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.
Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);
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).
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 ','
.
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).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With