Java implements CSV field segmentation

  • 2020-04-01 04:02:35
  • OfStack

Support for nested quotes, comma splitting


private static String[] cvsField(String line){
    List<String> fields = new LinkedList<>();
    char[] alpah = line.toCharArray();
    boolean isFieldStart = true;
    int pos = 0; int len = 0; boolean yinhao = false;
    for(char c : alpah){
      if(isFieldStart){
        len = 0;
        isFieldStart = false;
      }
      if(c == '"'){
        yinhao = !yinhao;
      }
      if(c == ',' && !yinhao){
        fields.add(new String(alpah, pos - len, len));
        isFieldStart = true;
      }
      pos++; len++;
    }
    return fields.toArray(new String[0]);
  }

The above is all the content of this article, I hope you can enjoy it.


Related articles: