只要通过你的字符串。如果您处于“阻止”状态,则在您穿过字符串时请保持轨迹
。如果你是 - 不要将逗号作为
逗号(作为分隔符)。否则,请像这样对待它。这是一个简单的
算法,我会自己写。当你遇到第一个“你输入
一个块。当你遇到下一个”,你结束了你的那个块,等等。
所以你可以通过你的字符串一次。
import java.util.ArrayList;
public class Test003 {
public static void main(String[] args) {
String s = " John, , , , \" Barry, John \" , , , , , Doe, \"Sid , Nency\", Smith ";
StringBuilder term = new StringBuilder();
boolean inQuote = false;
boolean inTerm = false;
ArrayList<String> terms = new ArrayList<String>();
for (int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if (ch == ' '){
if (inQuote){
if (!inTerm) {
inTerm = true;
}
term.append(ch);
}
else {
if (inTerm){
terms.add(term.toString());
term.setLength(0);
inTerm = false;
}
}
}else if (ch== '"'){
term.append(ch); // comment this out if you don't need it
if (!inTerm){
inTerm = true;
}
inQuote = !inQuote;
}else if (ch == ','){
if (inQuote){
if (!inTerm){
inTerm = true;
}
term.append(ch);
}else{
if (inTerm){
terms.add(term.toString());
term.setLength(0);
inTerm = false;
}
}
}else{
if (!inTerm){
inTerm = true;
}
term.append(ch);
}
}
if (inTerm){
terms.add(term.toString());
}
for (String t : terms){
System.out.println("|" + t + "|");
}
}
}
它看起来像你处理CSV输入?如果是这样,*请*使用CSV库 - 有很多好的,它会为您节省很多的痛苦!如果您不是,请澄清您的问题,以解释为什么CSV库不适合... –
不,它不是一个CSV文档。这只是一个字符串 – Andrei
RB,如果你给我看,我会很高兴,我怎么能用Csv Lib来处理这个问题 – Andrei