Android replace double quotes with one quote [dupl

2019-09-30 20:15发布

问题:

This question already has an answer here:

  • replace String with another in java 5 answers

The string output is "data", "data1", "data2", "data3"

i want it to replace " with ' so the string output will be 'data', 'data1', 'data2', 'data3'

Thanks :)

回答1:

use String class replaceAll method

Syntax: public String replaceAll (String regularExpression, String replacement)

In your case

String str = "data", "data1", "data2", "data3";
str = str.replaceAll("\"", "'");
System.out.println(str);

Then you will get output as

'data','data1','data2','data3'

From Android API, replaceAll says

Matches for regularExpression within this string with the given replacement.

If the same regular expression is to be used for multiple operations, it may be more efficient to reuse a compiled Pattern.



回答2:

simply use String class to make this happen like:

String s = "data";
        String replace = s.replace( "\"",  "'");
        System.out.println(replace);


回答3:


Method 1: Using String replaceALL

 String myInput = "\"data1\",\"data2\",\"data3\",\"data4\",\"data5\"";
 String myOutput = myInput.replaceAll("\"", "'");
 System.out.println("My Output with Single Quotes is : " +myOutput);        

Output:

My Output with Single Quotes is : 'data1','data2','data3','data4','data5'

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "\"data1\",\"data2\",\"data3\",\"data4\",\"data5\"";
 String myOutputWithRegEX = Pattern.compile("\"").matcher(myInput).replaceAll("'");
 System.out.println("My Output with Single Quotes is : " +myOutputWithRegEX);            

Method 3: Using Apache Commons as defined in the link below:

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)