0

我有一个 txt 文件,如下所示:

1 5 7 5
4 8 19 6
23 56 78 9

我想读取所有这些值并将它们写入新文件,但顺序不同。

输出文件应如下所示:

1 4 23
5 8 56
7 19 78
5 6 9

现在我正在尝试将所有内容读入数组,但我不确定以后如何处理这些数据......

string line;
        using (StreamReader sr = new StreamReader(@"C:\Users\as\Desktop\file\1.txt", Encoding.Default))
        {
            line = sr.ReadToEnd();
            string[] lines = line.Split('\n');
            string newLine = lines[0].ToString();
        }

我的输入文件甚至可以有多达 400000 列。

编辑2:

我试过这样,但还是不行,有什么建议吗?

using (StreamReader sr = new StreamReader(@"C:\Users\as\Desktop\files\1.txt", Encoding.Default))
            {
                List<string> list = new List<string>();
                while ((line = sr.ReadLine()) != null)
                {
                    list.Add(line);
                }
                int valuesNumber = list[0].Split(' ').Count();

                List<string> final = new List<string>();

                for (int j = 0; j < valuesNumber ; j++)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        string[] stringArray = list[i].Split(' ');
                        final .Add(stringArray[j]);

                    }
                }
                using (StreamWriter writer = new StreamWriter(@"C:\Users\as\Desktop\files\2.txt", true))
                {
                    foreach (string item in result)
                    {
                        writer.WriteLine(item.ToString());
                    }
                }
            }

但我仍然得到前一个下的每个数字,如下所示:

1
4
23
5 
8
56
7
19
78
5
6
9
4

6 回答 6

1

这可以满足您的需求(它是完整的控制台应用程序,因此您可以自己玩)。根据您在帖子中的示例,这假设您每行始终具有相同数量的“列”。我省略了对文件的读/写以保持代码简洁。

using System.Collections.Generic;
using System.Linq;

namespace ChangeOrder
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            list.Add("3 5 7 2");
            list.Add("13 15 17 12");
            list.Add("23 25 27 22");

            int numberOfValuesPerLine = list[0].Split(' ').Count();

            List<string> result = new List<string>();

            for (int j = 0; j < numberOfValuesPerLine; j++)
            {
                for (int i = 0; i < list.Count; i++)
                {                    
                    string[] stringArray = list[i].Split(' ');
                    result.Add(stringArray[j]);    
                }                    
            }
        }
    }
}
于 2013-11-04T14:30:43.063 回答
0

If memory isn't an issue, you can use line.Split(' ') to turn each line into an array and then a Transpose method to rotate your array of arrays.

That might look like:

using (StreamReader sr = new StreamReader(@"C:\Users\as\Desktop\file\1.txt"))
{
    string allLinesAsString = sr.ReadToEnd();
    string[] lines = allLinesAsString.Split('\n');
    string[][] allLines = lines.Select(line => line.Trim().Split(' ')).ToArray();
    var rotatedLines = allLines.Transpose().ToList();
    string rotatedLinesAsString = string.Join(Environment.NewLine,
                                rotatedLines.Select(x => string.Join(" ", x)));
    // write rotatedLinesAsString to a file
}

If the file is too large to do this all in-memory, you could write code to work with FileStreams at a lower level. It would mean two reads through the file and a lot of seeking, but would lower the memory requirement to practically nothing. In pseudocode, that would be something like:

file_stream = open(input_file)
line_indexes = file_stream.indexes_of('\n')
output_stream = (output file)
loop
    output_stream.write(next item from each line_index)
    move each line_index past the just-read item
end when you reach the end of the line
于 2013-11-04T14:46:03.310 回答
0

引用真的很简单,你将这些行读入一个数组。然后,您需要将每一行拆分为一个数组。与您的示例的分离似乎是一个空白,所以如果该行是:

1 5 7 5

您需要将其拆分为一个数组:

var currentLineColumn = currentLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

所以你的数组现在看起来像:

1
5
7
5

你对每一行都做同样的事情......

于 2013-11-04T14:26:26.280 回答
0

在不解决性能问题的情况下,我可以想到一种可行的方法。我在这里非常粗略地介绍它,但您应该能够对此进行编码。

1)确定列数。创建一个包含那么多行的数组

2)在文件开头插入换行符

3) 将计数器设置为 1

4)在每个换行符之后,将每个连续的项目附加到连续的行

5)重复直到迭代次数=列数(每行处理完后插入换行符)

编辑:再考虑一分钟。上面编辑。

于 2013-11-04T14:31:07.453 回答
0

假设所有行都具有相同的长度(在您的示例中,每行 4 个元素):

        using (StreamReader sr = new StreamReader(@"C:\Users\as\Desktop\file\1.txt", Encoding.Default))
        {
            string content = sr.ReadToEnd();
            string[] lines = content.Split('\n');

            string[][] matrix = new string[lines.Length][];
            for (int i = 0; i < lines.Length; i++)
            {
                matrix[i] = lines[i].Split(' ');
            }

            //print column by column
            var rowLength = matrix[0].Length; // assuming every row has the same length

            //for each column
            for (int i = 0; i < rowLength; i++)
            {
                //print each cell
                for (int j = 0; j < matrix.Length; j++)
                {
                    Console.WriteLine(matrix[j][i]);
                }
            }
        }
于 2013-11-04T14:34:24.953 回答
0

我不太相信放弃代码,所以我将向您展示一些伪代码:

//define rows as a two dimensional array.
rows := [][]

reader := read_file("1.txt")

pointer:= 0

for each line in the file
    row := line.Split(" ") // So put each number into it's own array slow.
    rows[pointer] := row.
    pointer := pointer +1 // Increase pointer.

现在您已经获得了所有行的列表,您想从中创建列。

newRows := [][]

for x = 0 to rows.length
    for y = 0 to rows[x].length
        // Cycle through all values in multidimensional array.
        newRows[y][x] := rows[x][y] 

然后您可以将每个值打印到文件中。

于 2013-11-04T14:34:40.563 回答