Get count of all commas in a each line from csv fi

2019-07-19 10:28发布

问题:

What I'm trying to accomplish is to read CSV file and get the count of commas in each row. ALL CSV files are identical. Have 9 columns and they are separated by (,) So I wrote a simple function that reads the files and using foreach loop I read each line in the file.

public static void readCSVFile(string path)
   {
      string _path = path;

      string [] text = File.ReadAllLines(_path);

      foreach (string line in text)
      {
          string currentLine = line;
          Console.WriteLine("\t" + line);
      }

   }

So typically currentLine will have an output like this:

number , 10/21/14 07:01:10, 00:28:29, number (name), number; number (name), number, number (name), N/A, number

There're total of eight , in the line. How can I programmatically get the total number of commas in each line, so I can do something like this in my foreach loop:

foreach (string line in text)
{
   string currentLine = line;

   if (totalNumberOfCommas == 8)
   {
        //do something
   }
   else
   {
        //do something else
   }

回答1:

If you just want to count the commas, you can take advantage of the fact that string implements IEnumerable<char>, so you can use Count like this:

var commas = line.Count(c => c == ',');


回答2:

One way would be to use the String.Split functionality.

foreach (string line in text)
{
   string currentLine = line;

   string[] eachColumn = currentLine.Split(',');

   if (eachColumn.Length == 9)
   {
        //do something
   }
   else
   {
        //do something else
   }
}

Note that this will not work properly if you have commas in your actual data (not as a field separator). You should probably look into a csv parser to help with this sort of thing.



回答3:

You could try something like this

foreach (string line in text)
{
   string currentLine = line;
   int totalNumberOfCommas = currentLine.Split(',').Length - 1;

   if (totalNumberOfCommas == 8)
   {
        //do something
   }
   else
   {
        //do something else
   }
}