1

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?

user2171584
  • 1,493
  • 3
  • 10
  • 5
  • 2
    There are many existing CSV parser lib. You should use one. – Denys Séguret Apr 12 '13 at 19:46
  • possible duplicate of [Splitting a csv file with quotes as text-delimiter using String.split()](http://stackoverflow.com/questions/15738918/splitting-a-csv-file-with-quotes-as-text-delimiter-using-string-split) – Denys Séguret Apr 12 '13 at 19:50

1 Answers1

7

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;
}   
Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155