简体   繁体   English

在 2d 或锯齿状数组中用逗号和新空格分割字符串并在 c# 中访问项目

[英]split string with comma and newspace in 2d or jagged array and access items in c#

Hi there I have a text file like this, many lines 2 columns您好,我有一个像这样的文本文件,多行 2 列

CF7CED1BF035345269118A15EF2D45A06, product1
CF7CED1BF035345269118A15EF2D45A09, product2
....
...
...
...

I need to split this and access each field, more precise I need to make a loop that creates many files like product1.txt product2.txt etc and will enclose the codes on its left.我需要拆分它并访问每个字段,更准确地说,我需要创建一个循环来创建许多文件,例如 product1.txt product2.txt 等,并将代码放在其左侧。

So I need to create files with filenames of columns [2] of all lines and enclose the column[1] as value of each line所以我需要使用所有行的列 [2] 的文件名创建文件,并将列 [1] 作为每行的值括起来

I know how to do basic stuff in arrays, like read all lines and store them, but i don't know how to make a loop that will read both field 1 then 2 of LINE 1, create the file and store (I know how to read and save to file) and go on on next LINE 2 and go on field 1 and field 2 again and so on.我知道如何在数组中做基本的事情,比如读取所有行并存储它们,但我不知道如何创建一个循环来读取 LINE 1 的字段 1 和 2,创建文件并存储(我知道如何读取并保存到文件)并继续下一个 LINE 2 并再次进入字段 1 和字段 2,依此类推。

Someone suggested using jagged arrays would be faster than 2d arrays有人建议使用锯齿状数组会比二维数组更快

"When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient." “当你使用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);
}

Do you need to keep the contents for any further use?您是否需要保留内容以供进一步使用? if the intent is to read and the save the contents to separate files then there is no need for a separate array.如果目的是读取并将内容保存到单独的文件中,则不需要单独的数组。

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.

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