Question

I have a String containing: 'abc' 'abc' 'abc'. How can i use replaceAll, to produce: "abc" "abc" "abc" ?

I tried using

StringA=StringA.replaceAll(''','"');
Was it helpful?

Solution

The method to replace every occurrence of a char by another char is replace().

The char literal for a single quote is '\'' (the single quote must be escaped, so that it's not interpreted as the end of the char literal).

So you want

s = s.replace('\'', '"');

replaceAll(), suggested by many other answers, replaces substrings matching a regexp by another substring. It's less appropriate than the method replacing a single char by another one.

Side note: please respect the Java naming conventions. Variables start with a lowercase letter. Only class names start with an uppercase letter.

OTHER TIPS

StringA = StringA.replace('\'', '\"');

Even though it's called replace and not replaceAll, what it actually does is replace all occurrences of one character with the other:

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

This is more efficient than using the replaceAll version which replaces strings.

Use \ before double quote.

StringA = StringA.replaceAll("'","\"");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top