CSV文件内容转换为二维数组 [英] CSV file contents to two dimensional array
问题描述
这个问题已经用不同的输入多次问过,所以我想根据自己的要求重新发布它。
我有一个CSV文件,该文件以方式显示字符串字段
idnum,name1,name2,groupid
idnum,name1,name2,groupid
idnum,name1,name2,groupid
示例
s001,sahil,payap,gid0
s002,阿米尔,汗,gid02
d003, hrithik,roshan,gid03
我有二维字符串数组。我想逐行读取我的二维数组。
读取时应该是这样
arr [0] [0] = s001
arr [0] [1] = name1
arr [0] [2] = name2
arr [0] [3] = gid01
arr [1] [0] = s002
arr [1] [1] = Amir
arr [1] [2] =可汗
arr [1] [3] = gid04
一个文件中有40条记录它应该读到文件末尾。
我需要在C#中实现这一点
任何代码示例或任何解释都将对您有所帮助。
我对csv文件处理一无所知,所以请不要问您尝试了什么,至少如果您能给我一个仅读取一个变量字符串的代码示例,那将是一个很大的帮助。
而且请不要要求其他解决方案。
谢谢。
必须逐行读取文件。每行都必须使用 String.Split
分隔。然后,必须使用 Trim
修剪结果字符串,最后必须将其写入当前行的相应列中。但是我完全赞同上面的评论。更为方便的方法是使用某些名为 Person
的类或结构,然后解析为 List< Person>
。 / p>
可以按以下方式进行读取:
字符串行=字符串。空;
System.IO.StreamReader文件=新的System.IO.StreamReader( c:\\file.txt);
while(((line = file.ReadLine())!= null)
{
String [] parts_of_line = line.Split(',')
for(int i = 0; i< parts_of_line.Length; i ++)
parts_of_line [i] = parts_of_line [i] .Trim();
//处理行的任何部分
}
This question has been asked several times with different inputs so I thought of reposting it with my requirement.
I have a CSV file which contents string fields in the way given below.
idnum,name1, name2,groupid
idnum,name1, name2,groupid
idnum,name1, name2,groupid
example
s001,sahil,payap,gid0
s002,Amir,Khan,gid02
d003,hrithik,roshan,gid03
I have two dimensional string array. I want to read row by row to my two dimensional array. When it read it should be like this
arr[0][0]=s001
arr[0][1]=name1
arr[0][2]=name2
arr[0][3]=gid01
arr[1][0]=s002
arr[1][1]=Amir
arr[1][2]=Khan
arr[1][3]=gid04
there are 40 records in a file and it should read till the end of the file. I need to implement this in C#
Any code sample or any explanation would be great help.
I have no knowledge in csv file handling so please don't ask what did you try, at least if you could give me a code sample for reading just one string for a variable it would be a great help. And please don't ask to go for another solution. Thanks.
The file would have to be read in line-wise. Each line would have to be separated using String.Split
. Then the resulting strings would have to be trimmed using Trim
, and finally would have to be written into the respective columns of the current row. However I totally second the comments above; more convenient would be to use some class or struct called Person
and then to parse into a List<Person>
.
The reading could be done as follows:
String line = String.Empty;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\file.txt");
while((line = file.ReadLine()) != null)
{
String[] parts_of_line = line.Split(',')
for ( int i = 0; i < parts_of_line.Length; i++ )
parts_of_line[i] = parts_of_line[i].Trim();
// do with the parts of the line whatever you like
}
这篇关于CSV文件内容转换为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!