我有一個看起來像這樣的文本檔案
- 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 ;
}
我試過了,但字符之間沒有空格。所以,我在考慮這個。
uj5u.com熱心網友回復:
我會選擇這樣的東西:
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);
希望這可以幫助。如果我的回答仍然不能幫助你,請告訴我,我會更新我的答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535624.html
標籤:C#文件
