[英]Creating 2d array from a text file
I have a text file that looks like this我有一个看起来像这样的文本文件
in a N x N grid.在 N x N 网格中。 using c# I need to take the text file and turn it into a 2d array of string so that I can manipulate each character on an independent level.使用 c# 我需要获取文本文件并将其转换为二维字符串数组,以便我可以在独立的级别上操作每个字符。 Please help.There is no blank between characters.请帮助。字符之间没有空格。
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++;
}
I tried this but there is no spaces between characters.我试过了,但字符之间没有空格。 So, I'm thinking about this.所以,我在考虑这个。
I would go with something like this:我会 go 这样的事情:
var lines = File.ReadAllLines(path);
And now you can access each character.现在您可以访问每个角色。 For instance, if you want the 3rd character from line 7, you can get it by lines[6][2]
.例如,如果您想要第 7 行的第 3 个字符,您可以通过lines[6][2]
获取它。
You will need to add an import, if you have not already:如果您还没有,则需要添加导入:
import System.IO;
If you want to convert it to digits also, you can do a method like this:如果你也想把它转换成数字,你可以这样做:
// 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;
}
And then you would call it like this:然后你会这样称呼它:
var digit = AccessDigit(lines, 6, 2);
Hope this helps.希望这可以帮助。 If my answer still does not help you, please tell me and I'll update my answer.如果我的回答仍然不能帮助你,请告诉我,我会更新我的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.