将字符串数组转换为整数数组'System.FormatException'



我尝试将 data1 字符串数组转换为 int 数组端 也许还有其他一些解决方案可以完成此任务,但如果可能的话,我想让它工作。

问题是当我开始问题时,它停止并给我以下问题:"mscorlib 中发生了类型为'System.FormatException'的未处理异常.dll"我也用int.parse同样的责备。

static int[] data()
            {
                StreamReader house = new StreamReader("text.txt");
                while (!house.EndOfStream)
                {
                    s = house.ReadLine();
                    Console.WriteLine(s);
                }
                string[] data1 = s.Split(' ');
                int[] database = new int[(data1.Length)];
                for (int j = 0; j < data1.Length; j++)
                {
                    database[j] = Convert.ToInt32(data1[j]);//Program stops here
                }
                return database;
            }

文本.txt看起来像这样(用空格"分隔的数字):

6 1 1
10 5 10
20 10 20
35 5 15
45 5 5 
60 10 25 
75 5 10 

感谢您的帮助!

可能一个空字符串进入了拆分字符串数组。

尝试在执行拆分时定义StringSplitOptions

 string[] data1 = s.Split(' ', StringSplitOptions.RemoveEmptyEntries);

您还可以检查循环中的空字符串:

for (int j = 0; j < data1.Length; j++)
{
     if (string.IsNullOrWhitespace(data1[j])
         continue;
     database[j] = Convert.ToInt32(data1[j]);//Program stops here
}
您可以使用

Int32.TryParse。但是,如果转换失败,则数组项比预期多。因此,最好使用列表。而且,您仅对文件的最后一行执行转换。"{"定位错误。最后但并非最不重要的一点是,您应该 Disponse() 流读取器对象。

            static int[] data()
            {
                List<int> database = new List<int>();
                StreamReader house = new StreamReader("text.txt");
                while (!house.EndOfStream)
                {
                    s = house.ReadLine();
                    Console.WriteLine(s);
                    string[] data1 = s.Split(' ');
                    for (int j = 0; j < data1.Length; j++)
                    {    
                        int value;
                        if (Int32.TryParse(data1[j], out value))
                            database.Add(value));
                    }       
                }
                house.Dispose();
                return database.ToArray();
            }

你试过int Integer.parseInt(string)吗?

database[j] = Integer.parseInt(data1[j]);//Program stops here

另外,我会仔细检查那些切碎的字符串的内容是什么(例如,有一个换行符,最后一行是空白的......),所以用另一个字符包围显示它们,如"或[]...

最新更新