简体   繁体   English

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

[英]How to fix extra white-space issue in C# code?

I get an error when I get the numbers from a .txt file when I use extra spaces between numbers. 当我在数字之间使用多余的空格时,从.txt文件中获取数字时出现错误。 Example: 56 (space) (space) (space) 45 (space) (space) 6 (space) (space) (space) (space) (space) 2 789 示例:56(空间)(空间)(空间)45(空间)(空间)6(空间)(空间)(空间)(空间)(空间)2789

There is no problem when i use 1 space between numbers. 当我在数字之间使用1个空格时没有问题。 Example: 56 45 6 2 789 示例: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++;
    }
}

I'd expect normally works, but there's something wrong, and I don't get it. 我希望正常工作,但是出了点问题,但我不明白。

You can use TryParse to help you 您可以使用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++;
}

You can also try StringSplitOptions 您也可以尝试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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM