views:

220

answers:

3

Hi All.

I would like to trim a beginning and ending double quote (") from a string. how can I achieve that in java? thanks!

A: 

find indexes of each double quotes and insert an empty string there.

GK
But watch out for quotes in the middle...
David Gelhar
so it should be first index and the last index of double qoute.
GK
+5  A: 

You can use String#replaceAll() with a pattern of ^\"|\"$ for this.

E.g.

string = string.replaceAll("^\"|\"$", "");

To learn more about regular expressions, have al ook at http://regular-expression.info.

That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.

BalusC
don't you think it will replaces all occurrences of double quotes with empty string rather then the first and the last.
GK
I'm not building a csv parser. i'm building a facebook app using tinyfbclient and for some reason it provides me the uid of the user with trailing and ending double quotes.
ufk
@ufk: This isn't a complex regex. You may otherwise want to hassle with a bunch of `String#indexOf()`, `String#substring()`, methods and so on. It's only a little tad faster, but it's much more code. @GK: Uh, did you read/understand the regex or even test it?
BalusC
i checked. it does not replace all occurrences of double quotes. only the first and the last.
ufk
sorry BalusC i am not good at Regex, as you have used replaceAll, i had a doubt on that.
GK
@GK the caret represents the beginning of the searched string, and the dollar sign represents its end. The backslash here "escapes" the following quote so it's treated as just a character. So this regex says, replace all occurrences of quote at the start, or quote at the end, with the empty string. Just as requested.
Carl Manaster
@GK: Carl's right. Also, `replace()` methods doesn't accept regex. They accept only a char or a literal string (charsequence). The `replaceAll()` method is the only accepting a regex to match character patterns for replacement.
BalusC
+2  A: 

To remove the first character and last character from the string, use:

myString = myString.substring(1, myString.length()-1);
Michael Myers
This only requires that the quotes should *guaranteed* be present. If there's no guarantee, then you'll need to check it first beforehand.
BalusC
@BalusC: Certainly. From my reading of the question, it seems that the string is already known to have quotes around it.
Michael Myers