Created
November 17, 2020 07:34
-
-
Save hexbinoct/77f48386af63d49e75df12700f264653 to your computer and use it in GitHub Desktop.
Split csv line with commas and quotes in data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static List<string> single_line_process2(string line) | |
| { | |
| List<string> lineparts = new List<string>(); | |
| List<char> this_section = new List<char>(); | |
| bool quoteson = false; | |
| //Action<int> act = (int a) =>{ a = 6; }; | |
| Func<int, bool> islineend = (int i) => { return i >= line.Length - 1 ? true : false; }; | |
| Action<char> addtosection = (c) => { this_section.Add(c); }; | |
| Action newsection = () => { | |
| lineparts.Add(new string(this_section.ToArray())); | |
| this_section = new List<char>(); | |
| }; | |
| for (int i = 0; i < line.Length; i++) | |
| { | |
| var c = line[i]; | |
| if (c == '\"') | |
| { | |
| if (quoteson) | |
| { | |
| if (!islineend(i) && line[i +1]=='\"') | |
| { | |
| addtosection('\"'); | |
| i++; | |
| continue; | |
| } | |
| else | |
| { | |
| newsection(); | |
| i++; //we are at double quotes and they are ending, next will be comma and shud be skipped. | |
| quoteson = false; | |
| } | |
| } | |
| else | |
| { | |
| quoteson = true; | |
| continue; | |
| } | |
| } | |
| else if (c == ',') | |
| { | |
| if (quoteson) | |
| { | |
| addtosection(c); | |
| continue; | |
| } | |
| else | |
| { | |
| newsection(); | |
| } | |
| } | |
| else | |
| { | |
| addtosection(c); | |
| if (islineend(i)) | |
| newsection(); | |
| } | |
| } | |
| return lineparts; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment