如何解决C#代码中多余的空格问题?



当我在数字之间使用额外的空格时,当我从.txt文件中获取数字时,我会收到错误。示例:56 (空间

( (空间( (空间( 45 (空间( (空间( 6 (空间( (空间( (空间( (空间( 2 789当我在数字之间使用 1 个空格时没有问题。示例:56 45 6 2 789

for (int i = 0; i < count; i++)
{
string[] temp2;
temp2 = ReadText[i].Split(' ');
for (int a = 0; a < temp2.Length; a++)
{
Value[ValueCount] = float.Parse(temp2[a]);
ValueCount++;
}
}

我希望正常有效,但有些问题,我不明白。

您可以使用TryParse来帮助您

for (int i = 0; i < count; i++)
{
string[] temp2;
temp2 = ReadText[i].Split(' ');
for (int a = 0; a < temp2.Length; a++)
if (float.TryParse(temp2[a], out Value[ValueCount]))
ValueCount++;
}

您也可以尝试StringSplitOptions

for (int i = 0; i < count; i++)
{
string[] temp2;
temp2 = ReadText[i].Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
for (int a = 0; a < temp2.Length; a++)
Value[a] = float.Parse(temp2[a]);
}

最新更新