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
}
如果您只想计算逗号,可以利用字符串实现IEnumerable<char>
这一事实,因此您可以像这样使用Count
:
var commas = line.Count(c => c == ',');
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.
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.