Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am reading content of a csv file to a string array.
My problem is the content of file contains ',' in some of strings.
Those strings are shown in file in between "".
Now problem is i am splitting each line using ',' and those lines which contains ',' in its strings they are displaying more columns.
Below i am giving an example of such string:
abc,28384,"this,comma",8673,xyz,

Can anybody tell me how can i split such line.

Thanks,
Nagendra.
Posted

You can't use String.Split to do this.

You'll have to eitehr use a regex to split the strings or write your our parser that keeps track of open and closing quote marks.

I suggest the regex method. You can find a lot of information on it in these[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Jul-11 4:09am    
This is not enough. The problem appears to be a bit more difficult.
Please look at my answer to see why -- it's in the article's source code.
--SA
Use this regex
".*"|[^,]+
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Jul-11 4:08am    
No, it's not so easy.
Please look at my answer to see why -- it's in the article's source code.
--SA
The algorithm is not that simple. I happened to have the solution with full source code, only the delimiter is blank space. I've done this to created a facility to test command line with parameters containing blank spaces guarded with quotation mark. I wanted to do testing not using actual command line. You only need to replace blank space character with comma.

Let me show how to locate it. Go to may article: Enumeration-based Command Line Utility[^], locate the section "6. CommandLine Testing" — it explains the class CommandLineSimulationUtility. Download the source code and locate this class in a test/demo application.

Enjoy.

—SA
 
Share this answer
 
Write your custom split method, it's not that hard. Or (lazy, quite ineffective and error-prone solution) first split your string by ," and ", strings, then split each part by comma
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Jul-11 4:08am    
No, it's not so easy.
Please look at my answer to see why -- it's in the article's source code.
--SA
Timberbird 3-Jul-11 4:32am    
Yes - I realize now I was too quick to answer :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900