2

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?

2

1 Answer 1

11

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Don't copy the answer of another question, just comment to point it's a duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.