我从一个文本文件中读取,有时我会输入一个字符串:
;onor Oyj,Native,Uor Oyj1,"Uponor Oyj, UBS, Innovation AB",39639d4d26:-21f7;
我需要像这样拆分字符串:
'onor Oyj',
'Native',
'Uor Oyj1',
'Uponor Oyj, UBS, Innovation AB',
'39639d4d26:-21f7',
';'
我该怎么做?
答案 0 :(得分:1)
类似的东西:
String str = ";onor Oyj,Native,Uor Oyj1,\"Uponor Oyj, UBS, Innovation AB\",39639d4d26:-21f7;";
char[] c = str.toCharArray();
boolean inQuote = false;
for (int i = 0; i < c.length; i++)
{
if (c[i] == ',' && !inQuote)
c[i] = '\01'; // some value that doesn't appear in the string
if (c[i] == '"')
inQuote = !inQuote;
}
String[] arr2 = String.valueOf(c).split("\\01");
for (String s: arr2)
{
System.out.println(s);
}
输出:
;onor Oyj
Native
Uor Oyj1
"Uponor Oyj, UBS, Innovation AB"
39639d4d26:-21f7;
将String[] arr2 = String.valueOf(c).split("\\01");
替换为String[] arr2 = String.valueOf(c).replaceAll("\"", "").split("\\01");
以删除引号。