繁体   English   中英

从文本文件创建二维数组

[英]Creating 2d array from a text file

我有一个看起来像这样的文本文件

  • 1234567891
  • a12b13c14d
  • 2122232425
  • 3132333435
  • 4142434445
  • 5152535455
  • 6162636465
  • 7172737475
  • 8182838485
  • 9192939495

在 N x N 网格中。 使用 c# 我需要获取文本文件并将其转换为二维字符串数组,以便我可以在独立的级别上操作每个字符。 请帮助。字符之间没有空格。

String input = File.ReadAllText( @"c:\myfile.txt" );

int i = 0, j = 0;
string[,] result = new string[10, 10];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        result[i, j] = int.Parse(col.Trim());
        j++;
    }
    i++;
}

我试过了,但字符之间没有空格。 所以,我在考虑这个。

我会 go 这样的事情:

var lines = File.ReadAllLines(path);

现在您可以访问每个角色。 例如,如果您想要第 7 行的第 3 个字符,您可以通过lines[6][2]获取它。

如果您还没有,则需要添加导入:

import System.IO;

如果你也想把它转换成数字,你可以这样做:

// somewhere outside the method you should have read the lines and stored them in a variable:
var lines = File.ReadAllLines(path);

// the method to access a position and convert it to digit
int AccessDigit(string[] lines, int row, int col)
{
    // code that checks if row and col are not outside the bounds should be placed here

    // if inside bounds, we can try to access and convert it
    var isDigit = int.TryParse(lines[row][col], out int digit);

    return isDigit ? digit : -1;
}

然后你会这样称呼它:

var digit = AccessDigit(lines, 6, 2);

希望这可以帮助。 如果我的回答仍然不能帮助你,请告诉我,我会更新我的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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