Android replace double quotes with one quote [dupl

2019-09-30 20:18发布

This question already has an answer here:

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 :)

3条回答
放我归山
2楼-- · 2019-09-30 20:53

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.

查看更多
淡お忘
3楼-- · 2019-09-30 20:59

simply use String class to make this happen like:

String s = "data";
        String replace = s.replace( "\"",  "'");
        System.out.println(replace);
查看更多
趁早两清
4楼-- · 2019-09-30 20:59

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)

查看更多
登录 后发表回答