[英]split string with comma and newspace in 2d or jagged array and access items in c#
您好,我有一個像這樣的文本文件,多行 2 列
CF7CED1BF035345269118A15EF2D45A06, product1
CF7CED1BF035345269118A15EF2D45A09, product2
....
...
...
...
我需要拆分它並訪問每個字段,更准確地說,我需要創建一個循環來創建許多文件,例如 product1.txt product2.txt 等,並將代碼放在其左側。
所以我需要使用所有行的列 [2] 的文件名創建文件,並將列 [1] 作為每行的值括起來
我知道如何在數組中做基本的事情,比如讀取所有行並存儲它們,但我不知道如何創建一個循環來讀取 LINE 1 的字段 1 和 2,創建文件並存儲(我知道如何讀取並保存到文件)並繼續下一個 LINE 2 並再次進入字段 1 和字段 2,依此類推。
有人建議使用鋸齒狀數組會比二維數組更快
“當你使用ReadLines時,你可以在返回整個集合之前開始枚舉字符串的集合;當你使用ReadAllLines時,你必須等待返回整個字符串數組才能訪問數組。因此,當你在工作時對於非常大的文件,ReadLines 可以更有效率。”
string path_read = @"c:\read\file.txt";
//Path to save resulting files.
string path = @"c:\temp\";
char[] comma = new char[1]{','};
//ASSUMPTION: Your every row has comma separated 2 values.
//Do a for loop.
//Code now use File.ReadLines
foreach (var currentLine in File.ReadLines(path_read))
{
string[] itemArray = currentLine.Split(comma, StringSplitOptions.RemoveEmptyEntries);
// Your item array now has 2 values from 2 columns in the same row.
// Do whatever with it.
File.WriteAllText(path+itemArray[1]+".txt", itemArray[0], Encoding.UTF8);
}
您是否需要保留內容以供進一步使用? 如果目的是讀取並將內容保存到單獨的文件中,則不需要單獨的數組。
using (var reader = new StreamReader(@"input.txt"))
{
while (!reader.EndOfStream)
{
var inputText = reader.ReadLine();
var splitText = inputText.Split(',');
File.AppendAllLines(splitText[1] + ".txt", new List<string> {splitText[0]});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.