如何用Java String中的单个双引号替换两个双引号? [英] How to replace two double quotes with a single double quote in Java String?
本文介绍了如何用Java String中的单个双引号替换两个双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读一个CSV文件并有一些值,如
I am reading a CSV file and have some values like
field 1 field 2 field 3
1 test case1 expecting one, and \"two\", and three
将文件读入 StringBuilder
并转换 toString()
我将文件内容拆分为: string.split(, (?=([^ \ ] * \[^ \ ] * \)* [^ \ ] * $));
after reading file into a StringBuilder
and converting toString()
I split the file content by: string.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
.
在迭代字符串时,我得到以下值: -
On iterating the string I get these values:-
1
test case1
expecting one, and ""two"", and three
我怎么能我将单引号替换为两个双引号,如此两个
How I can I replace two double quotes with single double like this "two"
这是我的代码: -
here is my code:-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class csvStringParser {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String path = "E:/spc.csv";
String read = readFile(path);
System.out.println("content of the file before \" = \n" +read);
// System.out.println("content of the file after= \n" +read);
String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(int i = 0;i<tokens.length;i++) {
String abc = tokens[i].replace("\"\"", "\"");
// if(abc.length()>2){
if(abc.startsWith("\"") && abc.endsWith("\"")){
abc = abc.substring(1, abc.length()-1);
}
// }
System.out.println("> "+abc);
}
}
public static String readFile( String file ) throws IOException {
BufferedReader reader = new BufferedReader( new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
}
}
推荐答案
使用 String#replace(CharSequence,CharSequence)
。
String input = "this string \"\"has\"\" double quotes";
String output = input.replace("\"\"", "\"");
这篇关于如何用Java String中的单个双引号替换两个双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文