0

I have below mentioned CSV string which I need to split using commas .

Input:
A,"Rakesh,Gaur",B,"A,B",Z

OutPut:

A
Rakesh,Gaur
B
A,B
Z
Rakesh
  • 313
  • 1
  • 3
  • 14

2 Answers2

0

You can't use string split or regular expressions. If you are not going to use a library that is already built, you have to keep track of whether or not you are in_quotes. but as you will find out after you start this: csv parsing is complex. You should use something that is already pre-built. As I recall from my days writing an app that heavily relied on csv, there are escape characters and such, that you will need to account for.

Either way the psuedo code is as follows:

Stack cells = m
in_quotes = false
foreach character in string:
  if character != ',' && character != '"':
    cells.Top = cells.Top + character

  else if character == ',' && in_quotes:
    cells.Top = cells.Top + character
  else if character == ',':
    cells.push("")

  else if character == '"' && in_quotes:
    in_quotes = false
  else if character == '"':
    in_quotes = true
leat
  • 1,418
  • 1
  • 15
  • 21
  • Why do you think that a regular expression can't be used? http://stackoverflow.com/questions/18144431/regex-to-split-a-csv – Guffa May 03 '15 at 09:23
  • As Guffa said, a general comment like "You can't use string split or regular expressions" is simply wrong. You *can*. Maybe you *shouldn't*, but that's another matter. As for your pseud-parser - you do not handle escaped quotes, and don't really validate the file. – Kobi May 03 '15 at 10:21
  • Is there any regular expression available for the same ? @leat: do you code smaple in c# for above mentioned code – Rakesh May 03 '15 at 10:41
  • @Kobi, That was my point, I don't handle escaping, but to do that properly I would do an LLR language parser/scanner, but that is where it gets way more complex, you should probably get a grammer and a parser. what do you do with non well formed documents? Its a challenge, regular expressions almost certainly will not handle that satisfactorily in a real world application in a singe method call. I would like the other question suggests use a pre-built Library. This was simply a starting point you COULD build that handles well formed document parsing and object model construction. – leat May 03 '15 at 18:49
0

I think you can do this using following steps:

string[] words = yourStringInput.Split(',');
foreach (string word in words)
{
    Console.WriteLine(word);
}
meOn
  • 194
  • 1
  • 12
  • 1
    That will split the value `"Rakesh,Gaur"` into two values, and it won't remove the quotes arond quoted values. – Guffa May 03 '15 at 09:11