[英]Trying to parse a text file line by line and split lines into a jagged array of words
我正在嘗試逐行讀取文件的每一行,並將這些單獨的行(進一步分成它們各自的“單詞”的數組)放入鋸齒狀的數組中,以便我可以進一步操作它們。 如果有人熟悉,我正在嘗試代碼挑戰賽的第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]);
}
}
}
我得到的錯誤是“無法將類型string []隱式轉換為字符串”
但是,鋸齒狀數組的每一行難道不應該是string[]
而不是string
嗎?
我一定會錯過這里幕后情況的一些基本方面。 我嘗試使用File.ReadAllLines
和File.ReadLines
並將它們也解析為字符串數組,但是問題總是歸結於在循環中實例化數組。 似乎無法使該工作。
也歡迎使用C#解決此問題的任何其他方法,我只是想更好地理解這個問題。
System.IO的File
類具有方法ReadAllLines
,可在此處使用。 要拆分每行並轉換為數組,請使用Select
和ToArray
Linq擴展方法( using
來添加必需的訪問方法)
using System.IO;
using System.Linq;
string[][] input = File.ReadAllLines(@"c:/theFilePath.txt")
.Select(x => x.Split(' '))
.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.