How to handle commas in the data of a csv in Java

蓝咒 提交于 2020-08-09 12:56:16

问题


I'm using scanner.delimiter to split my csv, with the delimiter being ",". However I have some data that includes commas in the data like "Monsters, Inc."

However if I set the delimiter to "\",\"", then it crashes on everything else.

Ideas that don't require me to write my own scanner.delimiter method?


回答1:


I don't think scanner.delimiter will work for this kind of problem. If you have quotes in the data where the extra comas exist, you can either use a regular expression or code to solve this kind of problem using also the String.split as mentioned in similar answers/questions. If you don't have quotations, then there is really nothing you can do.

There have been similar examples on stackoverflow. For example I think this one applies to you:

Splitting a csv file with quotes as text-delimiter using String.split()

Using Split

public static void main(String[] args) {
    String s = "Sachin,,M,\"Maths,Science,English\",Need to improve in these subjects.";
    String[] splitted = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
    System.out.println(Arrays.toString(splitted));
}

Using custom code

public static ArrayList<String> customSplitSpecific(String s)
{
    ArrayList<String> words = new ArrayList<String>();
    boolean notInsideComma = true;
    int start =0, end=0;
    for(int i=0; i<s.length()-1; i++)
    {
        if(s.charAt(i)==',' && notInsideComma)
        {
            words.add(s.substring(start,i));
            start = i+1;                
        }   
        else if(s.charAt(i)=='"')
        notInsideComma=!notInsideComma;
    }
    words.add(s.substring(start));
    return words;
}   


来源:https://stackoverflow.com/questions/15979688/how-to-handle-commas-in-the-data-of-a-csv-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!