I want to replace the last String which is a ",
" with ")
"
Suppose the string is
Insert into dual (name,date,
to be converted to
Insert into dual(name,date)
I want to replace the last String which is a ",
" with ")
"
Suppose the string is
Insert into dual (name,date,
to be converted to
Insert into dual(name,date)
The following code should replace the last occurance 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 ','
.
Check the length of the string, check the last char (if you have the length it is easy) and replace it - when necessary. This solution is not lang. specific. just use a common sense.
You can use regular expression:
String aResult = "Insert into dual (name,date,".replaceAll(",$", ")");
replaceAll(...)
will match string string with the given regular expression (parameter 1) (in this case we match the last character if it is a comma). The replace it with a replacement (parameter 2) (in this case is ')
').
Plus! If you want to ensure that tailing spaces and tabs are taken care of, you can just change the regex to ',\[ \t\]*$
'. NOTE '\[
' and '\]
' is without backslash (I don't know how to properly escape it).
Hope this helps.
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);