开发者

Reading comma in content of csv file (E.g. $1,23,456)

开发者 https://www.devze.com 2023-04-09 02:12 出处:网络
Using C# program I am reading CSV File with value like (Name, Salary, Age)(A,$1,200, 27) (B, 2300, 27)

Using C# program I am reading CSV File with value like (Name, Salary, Age) (A, $1,200, 27) (B, 2300, 27)

In the header row there are three columns. I want to validate that the number of columns in data rows is 开发者_开发百科also three. (C, 28) should be an invalid file.

Currently I am doing this by counting the number of commas. But when the content itself is having comma ($1,200), this logic is failing. How do I solve this issue?


Use library for reading csv files. Why are you wrintg it on yourown when someone already did it for you?. Last time i was reading csv i used CsvHelper.


As a fast answer why don you split by (", ")

var s  = "Name, Salary, Age";
var t = "A, $1,200, 27";
var x = "B, 2300, 27";

string[] stringSeparators = new string[] {", "};

s.Split(stringSeparators, StringSplitOptions.None).Dump();
t.Split(stringSeparators, StringSplitOptions.None).Dump();
x.Split(stringSeparators, StringSplitOptions.None).Dump();

Not the best solution but it's one that fits....

As was commented by @Tim Pietzcker it's not a valid csv file....

Anyway....


Could you perhaps do this?...where fileLine would be "A, $1,200, 27". This is assuming that each column is delineated by a comma then a space.

        int lastCommaIdx = fileLine.LastIndexOf(",");
        string agePart = fileLine.Substring(lastCommaIdx + 1, fileLine.Length - (lastCommaIdx + 1)).Trim();
        int age = Convert.ToInt32(agePart);

        fileLine = fileLine.Substring(0, lastCommaIdx);
        int dollarIdx = fileLine.LastIndexOf("$");
        string salary = fileLine.Substring(dollarIdx, fileLine.Length - dollarIdx).Trim();

        string name = fileLine.Substring(0, dollarIdx).Trim().TrimEnd(new char[1] { ',' });

        Debug.WriteLine(string.Format("Name={0}, Salary={1}, Age={2}", name, salary, age));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号