尝试逐行解析文本文件并将行拆分为锯齿状的单词数组
Trying to parse a text file line by line and split lines into a jagged array of words
我正在尝试逐行读取文件的每一行,并将这些单独的行进一步划分为各自的数组 "words" 放入锯齿状数组中,以便我可以进一步操作他们。如果有人熟悉我正在尝试 Advent of Code Challenge 的第 12 天,所以我的输入看起来像
0 <-> 780, 1330
1 <-> 264, 595, 1439
2 <-> 296, 531, 1440
我希望每一行都是
array[0][0] = 0
array[0][1] = <->
array[0][2] = 780
array[0][3] = 1330
array[1][0] = 1
... etc
我已经为此工作了一天,但我似乎无法让 C# 执行此操作。这是我一直在尝试的解决方案的最新成果
static void Main(string[] args)
{
string[][] input = new string[2000][];
string line;
System.IO.StreamReader file =
System.IO.StreamReader(@"c:/theFilePath.txt");
while ((line = file.ReadLine()) != null)
{
for (int i = 0; i < 2000; i++)
{
string[] eachArray = line.Split(null);
input[i] = new string[] { eachArray };
}
}
for (int i = 0; i < input.Length; i++)
{
for (int j = 0; j < input[i].Length; j++)
{
Console.WriteLine(input[i][j]);
}
}
}
我得到的错误是 "Cannot implicitly convert type string[] to string"
但是锯齿状数组的每一行不应该是 string[]
而不是 string
吗?
我一定是遗漏了这里幕后发生的事情的一些基本方面。
我尝试过使用 File.ReadAllLines
和 File.ReadLines
并将它们解析为字符串数组,但问题总是归结为在循环中实例化数组。似乎无法完成这项工作。
也欢迎使用 C# 解决此问题的任何其他方法,我只是想更好地理解这个问题。
File
class 来自 System.IO 的方法 ReadAllLines
可以在这里使用。
要拆分每一行并转换为数组,请使用 Select
和 ToArray
Linq 扩展方法(添加所需的 using
s 以访问提到的方法)
using System.IO;
using System.Linq;
string[][] input = File.ReadAllLines(@"c:/theFilePath.txt")
.Select(x => x.Split(' '))
.ToArray();
我正在尝试逐行读取文件的每一行,并将这些单独的行进一步划分为各自的数组 "words" 放入锯齿状数组中,以便我可以进一步操作他们。如果有人熟悉我正在尝试 Advent of Code Challenge 的第 12 天,所以我的输入看起来像
0 <-> 780, 1330
1 <-> 264, 595, 1439
2 <-> 296, 531, 1440
我希望每一行都是
array[0][0] = 0
array[0][1] = <->
array[0][2] = 780
array[0][3] = 1330
array[1][0] = 1
... etc
我已经为此工作了一天,但我似乎无法让 C# 执行此操作。这是我一直在尝试的解决方案的最新成果
static void Main(string[] args)
{
string[][] input = new string[2000][];
string line;
System.IO.StreamReader file =
System.IO.StreamReader(@"c:/theFilePath.txt");
while ((line = file.ReadLine()) != null)
{
for (int i = 0; i < 2000; i++)
{
string[] eachArray = line.Split(null);
input[i] = new string[] { eachArray };
}
}
for (int i = 0; i < input.Length; i++)
{
for (int j = 0; j < input[i].Length; j++)
{
Console.WriteLine(input[i][j]);
}
}
}
我得到的错误是 "Cannot implicitly convert type string[] to string"
但是锯齿状数组的每一行不应该是 string[]
而不是 string
吗?
我一定是遗漏了这里幕后发生的事情的一些基本方面。
我尝试过使用 File.ReadAllLines
和 File.ReadLines
并将它们解析为字符串数组,但问题总是归结为在循环中实例化数组。似乎无法完成这项工作。
也欢迎使用 C# 解决此问题的任何其他方法,我只是想更好地理解这个问题。
File
class 来自 System.IO 的方法 ReadAllLines
可以在这里使用。
要拆分每一行并转换为数组,请使用 Select
和 ToArray
Linq 扩展方法(添加所需的 using
s 以访问提到的方法)
using System.IO;
using System.Linq;
string[][] input = File.ReadAllLines(@"c:/theFilePath.txt")
.Select(x => x.Split(' '))
.ToArray();