从csv文件获取每一行中所有逗号的计数

从csv文件获取每一行中所有逗号的计数

本文介绍了从csv文件获取每一行中所有逗号的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要完成的工作是读取CSV文件并获取每行中的逗号计数。所有CSV文件都相同。有9列,它们之间用(,)隔开,所以我写了一个简单的函数来读取文件并使用 foreach 循环读取文件中的每一行。

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);
      }

   }

因此通常 currentLine 将具有以下输出:

So typically currentLine will have an output like this:

总共有八个。如何以编程方式获取每行中个逗号的总数,因此我可以在 foreach 中执行类似的操作循环:

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
   }


推荐答案

如果您只想要计算逗号,您可以利用字符串实现 IEnumerable< char> 的事实,因此可以使用 Count 像这样:

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 == ',');

这篇关于从csv文件获取每一行中所有逗号的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:06