简体   繁体   English

在C#中将TXT文件解析为2D字符串数组

[英]Parse TXT File Into 2D String Array in C#

I am looking for a way to parse a text file I have into a 2D String array with 9 rows and 7 columns. 我正在寻找一种方法来解析我拥有的文本文件到一个包含9行和7列的2D字符串数组。 Every Pip should be another column and every Enter should be another row. 每个Pip应该是另一列,每个Enter应该是另一行。 100|What color is the sky?|Blue,Red,Green,Orange|Blue

Here is the code I have so far but I don't know how to correctly parse it. 这是我到目前为止的代码,但我不知道如何正确解析它。

private void loadQuestions()
    {
        string line;
        string[,] sQuestionArray = new string[9, 7];
        System.IO.StreamReader file = new System.IO.StreamReader("questions.txt");
        while ((line = file.ReadLine()) != null)
        {

        }
        file.Close();
    }

Any help would be greatly appreciated. 任何帮助将不胜感激。

If you can use string[][] instead of string[,] then you can do 如果你可以使用string[][]而不是string[,]那么你可以做

string[] lines = File.ReadAllLines("questions.txt");
string[][] result = lines.Select(l => l.Split(new []{'|', ','})).ToArray();

Take a look at Split . 看看斯普利特

Ex: var splitLine=line.Split(new[] {',', '|'}); 例如: var splitLine=line.Split(new[] {',', '|'});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM