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
0

2 Answers 2

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

4 Comments

Why do you think that a regular expression can't be used? stackoverflow.com/questions/18144431/regex-to-split-a-csv
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.
Is there any regular expression available for the same ? @leat: do you code smaple in c# for above mentioned code
@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.
0

I think you can do this using following steps:

string[] words = yourStringInput.Split(',');
foreach (string word in words)
{
    Console.WriteLine(word);
}

1 Comment

That will split the value "Rakesh,Gaur" into two values, and it won't remove the quotes arond quoted values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.