[英]Convert string array to int array 'System.FormatException'
I try to convert the data1 string array to an int array end maybe there is some other solutions for this task but if its possible I want to make this working. 我尝试将data1字符串数组转换为int数组末尾,也许有其他解决方案可以完成此任务,但是如果可能的话,我想使它工作。
Problem is when I start the problem its got a stops and drops me the following problem: "An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll" I ryed also with int.parse same problame. 问题是,当我开始该问题时,它停了下来,并向我抛出以下问题:“ mscorlib.dll中发生了'System.FormatException'类型的未处理异常”,我也用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;
}
text.txt looks like this(digits separated with space " "): text.txt看起来像这样(数字之间用空格“”分隔):
6 1 1
10 5 10
20 10 20
35 5 15
45 5 5
60 10 25
75 5 10
Thank you for your help! 谢谢您的帮助!
Probably an empty string get into your array of splitted strings. 可能是空字符串进入了拆分字符串数组。
Try defining StringSplitOptions
when doing the split: 尝试在拆分时定义StringSplitOptions
:
string[] data1 = s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
You can also check for empty string inside your loop: 您还可以在循环中检查空字符串:
for (int j = 0; j < data1.Length; j++)
{
if (string.IsNullOrWhitespace(data1[j])
continue;
database[j] = Convert.ToInt32(data1[j]);//Program stops here
}
You can use Int32.TryParse. 您可以使用Int32.TryParse。 But if the conversion fails, you have an array item more than expected. 但是,如果转换失败,则您有比预期更多的数组项。 Therefore, it is better to use a List. 因此,最好使用列表。 And also, you are performing the conversion only for the last line of your file. 而且,您仅对文件的最后一行执行转换。 A '{' is located wrong. '{'位于错误的位置。 Last but not least, you should Disponse() the stream reader object. 最后但并非最不重要的一点是,您应该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();
}
Have you tried int Integer.parseInt(string)
? 您是否尝试过int Integer.parseInt(string)
?
database[j] = Integer.parseInt(data1[j]);//Program stops here
Also, I would check carefully what the contents of those chopped up strings are (eg, has a new-line character creeped in, is the last line blank...), so display them surrounded by another character, like " or [] ... 另外,我会仔细检查这些切碎的字符串的内容(例如,是否有换行符,最后一行是空白...),因此将其显示为另一个字符,例如“或[]” ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.