从文本文件中将字符串转换为整数数组

4

我写了下面这段代码以在C#语言中打开一个文本文件。文件中的每一行都包含五个数字,例如:

0    0    2    3     6

0    1    4    4     7

0    2    6    9     9

1    0    8    11    9

1    1    12   15    11

2    2    12   17    15

数字之间的距离为一个制表符。

问题在于当您执行程序时,会出现以下错误:

输入字符串格式不正确,位于 Convert.ToInt32(t[j])

代码:

string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
for (int i = 1; i < st.Length; i++)
{

   string[] t = st[i].Split(new char[] { ' ' });
   int cnt = 0;
   for (int k = 0; k < t.Length; k++)
        if (t[k] != "")
           { t[cnt] = t[k]; cnt++; }
        for (int j = 0; j < 5; j++)
                tmp[i - 1, j] = Convert.ToInt32(t[j]);
 }

我应该如何纠正这个问题?

8
提示:在任何地方都使用花括号,这样会使它更清晰。你目前似乎认为你的第二个“for”循环嵌套在第一个循环中。但实际上并不是这样。 - Jon Skeet
Convert.ToInt32(t[j]) 的输入不包含任何数字时,会出现错误 'input string was not in correct format in Convert.ToInt32(t[j])'。那么在那里设置一个断点并检查 t[j] 的值怎么样? - degant
3个回答

8

我建议将集合类型从2维数组int[,]更改为锯齿状类型int[][],然后使用Linq

 using System.Linq;

 ...

 int[][] data = File
   .ReadLines(@"C:\testing\result.txt")
   .Select(line => line
       // Uncomment this if you have empty lines to filter out:
       // .Where(line => !string.IsNullOrWhiteSpace(line)) 
      .Split(new char[] {'\t'}, StringSplitOptions.RemoveEmptyEntries)
      .Select(item => int.Parse(item))
      .ToArray())
   .ToArray();  

1

分割字符char应该是一个制表符'\t'而不是单个空格space


@Dmitry Bychenko,@ Bhuban:谢谢。 - zozo

0

每行有五个数字,但不一定是五个数字。您需要一个更复杂的解决方案,如下:

string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
bool isAlreadyNumber = false;
bool isEmptyRow = true;
int rowIndex = -1;
int colIndex = -1;
for (int i = 0; i < st.Length; i++) {
   isAlreadyNumber = false;
   isEmptyRow = true;
   foreach (char c in st[i]) {
      if ((c >= '0') && (c <= '9')) {
          if (isAlreadyNumber) {
              tmp[rowIndex][colIndex] = tmp[rowIndex][colIndex] * 10 + (c - '0');
          } else {
              tmp[rowIndex][colIndex] = c - '0';
              if (isEmptyRow) rowIndex++;
              isEmptyRow = false;
              isAlreadyNumber = true;
          }
      } else {
          isAlreadyNumber = false;
      }
   }
 }

请注意,索引已经修复。这段未经测试的代码还可以处理其他分隔符和空行,但仍然假定会有五个数字。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接