本文介绍了C#文本文件分割成一个二维字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,看起来像这样:

I have a textfile that looks like this :

John,Gauthier,blue,May
Henry,Ford,Red,June
James,Bond,Orange,December

我想将它分割成一个二维字符串数组,所以我可以每线分开那么每个单词。例如:

I want to split it into a two dimensional string array so I could separate each lines then each words. Ex:

mystring[0][0] = "John"
mystring[1][3] = "June"
mystring[2][2] = "Orange"

下面是我所做的现在:

string[] words = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");

while (fichier.Peek() != -1)
{
  i++;
  words = myfile.ReadLine().Split(',');

}

我卡住了。我可以把它拆分成一维字符串数组而不是变成一个二维字符串数组。我想我需要两次把它分解;用'\\ n'以及第二次用','然后第一次就把那两个在一起。

I'm stuck. I'm able to split it into a one dimensional string array but not into a two dimensional string array. I guess I need to split it two times ; First time with '\n' and the second time with ',' and then put those two together.

推荐答案

这实际上是一个班轮:

File.ReadLines("myfilename.txt").Select(s=>s.Split(',')).ToArray()

由于这是一个初学者的问题,这里发生了什么:

Since this is a beginner question, here's what's going on:

File.ReadLines(文件名)返回所有行的集合在文本文件中。

File.ReadLines(filename) returns a collection of all lines in your text file

。选择是一个扩展方法,它的函数

.Select is an extension method that takes a function

S => s.Split('')是函数,它通过拆分逗号所有字符串s,并返回​​一个字符串数组。

s=>s.Split(',') is the function, it splits the string s by all commas and returns an array of strings.

.ToArray()需要通过创建。选择字符串数组的集合,使阵列出来的,所以你得到数组的数组。

.ToArray() takes the collection of string arrays created by .Select and makes an array out of that, so you get array of arrays.

这篇关于C#文本文件分割成一个二维字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:56
查看更多