【问题标题】:Read rows/columns of numbers in a text file (c#)读取文本文件中数字的行/列(c#)
【发布时间】:2015-03-18 07:22:32
【问题描述】:

我有一个带有以下数字的文本文件,例如:

1 2 3
4 5 6

如何将每个单独的数字读入一个数组?

它需要沿每一行移动,因此将 1、2 和 3 读入一个数组,然后移动到第二行并读取 4 5 和 6.. 并显示文本框中的单元格数。

这是我的代码,但出现错误。

List<string> list2 = new List<string>();
    for (int i = 0; i < lines.Length; i++)
    {
        char[] chars = lines[i].ToCharArray();
        for (int j = 0; j < chars.Length; j++)
        {
            if (!Char.IsWhiteSpace(chars[j]))
                list2.Add(chars[j].ToString());
        }
    }

【问题讨论】:

  • 你得到的错误是什么?

标签: c# arrays winforms text textbox


【解决方案1】:

你可以把它转换成一个锯齿形的 int 数组:

int[][] result = text
            .Split('\n')
            .Select(line => 
                line
                .Split(' ')
                .Select(numberText => int.Parse(numberText))
                .ToArray()).ToArray();

这样迭代:

foreach (int[] line in result)
{
    Console.WriteLine(string.Join(", ", line)); // or iterate through its numbers again
                                                // or whatever you want to do
}

编辑

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

string path = "xy"; //your path
string[] lines = File.ReadAllLines(path);

int[][] result = lines
            .Select(line => 
                line
                .Split(' ')
                .Select(numberText => int.Parse(numberText))
                .ToArray()).ToArray();

foreach (int[] line in result)
{
    list2.Add(string.Join(", ", line)); // or whatever format you want the text to be
}

【讨论】:

  • do list2.Add(string.join(...)) 它也应该适用于您现有的代码...如果您使用您的行替换 text.Split('\n')使用 File.ReadAllLines
  • 你能告诉我,我应该在哪里换吗?
  • 很清楚,谢谢,如果我想在文本框中显示单元格的数量?
  • @Florian Schmidinger:我收到了这条消息:
  • 使用line.Length?数组的长度将是值的数量。
【解决方案2】:
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    label3.Text = openFileDialog1.FileName;
    textBox1.Text = File.ReadAllText(label3.Text);
    FileStream fs = File.OpenRead(label3.Text);
    string[] lines = new StreamReader(fs).ReadToEnd().Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
    fs.Close();
    List<string> list2 = new List<string>();
    for (int i = 0; i < lines.Length; i++)
    {
        char[] chars = lines[i].ToCharArray();
        for (int j = 0; j < chars.Length; j++)
        {
            if (!Char.IsWhiteSpace(chars[j]))
                list2.Add(chars[j].ToString());
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2020-08-16
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多