tags:

views:

1108

answers:

6

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)
+3  A: 

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

jjnguy
I think he tagged it as java, isn't stringbuilder a dotnet ?
Dani
Both languages have StringBuilder
jjnguy
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
Yeah, my solution will replace the last occurrence of a string even if it isn't the exact last character.
jjnguy
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
+1  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.

Dani
Its not the last character, its the last occurrence of a specific character.
jjnguy
Well, the question isn't clear about that. "the last string.." I wonder what he meant...
Dani
True, that's why I went for the method that would work in both cases.
jjnguy
A: 

In C# you could use the lastIndexOf method off the string class

Blake Taylor
Unfortunately he is using Java...which has that method too...
jjnguy
+1  A: 
str = str.substring(0, str.lastIndexOf(",")) + ")";
sfussenegger
That would change the last ",", indiscriminate if it is the last character in a String or not.
Martin Hohenberg
It works wherever ',' is located - it will ignore anything that follows the last ',' though.
sfussenegger
+2  A: 

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.

NawaMan
+1  A: 

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);
Martin Hohenberg
More readable than what?
sfussenegger