4

I was wanting to parse a string such as "10.0.20" into a number in order to compare another string with the same format in C#.net

For example I would be comparing these two numbers to see which is lesser than the other: if (10.0.30 < 10.0.30) ....

I am not sure which parsing method I should use for this, as decimal.Parse(string) didn't work in this case.

Thanks for your time.

Edit: @Romoku answered my question I never knew there was a Version class, it's exactly what I needed. Well TIL. Thanks everyone, I would have spent hours digging through forms if it wasn't for you lot.

4

2 回答 2

9

您尝试解析的字符串看起来像一个版本,因此请尝试使用Version该类。

var prevVersion = Version.Parse("10.0.20");
var currentVersion = Version.Parse("10.0.30");

var result = prevVersion < currentVersion;
Console.WriteLine(result); // true
于 2013-07-25T15:37:54.237 回答
1

版本看起来是最简单的方法,但是,如果您需要无限的“小数位”,请尝试以下方法

private int multiDecCompare(string str1, string str2)
    {
        try
        {
            string[] split1 = str1.Split('.');
            string[] split2 = str2.Split('.');

            if (split1.Length != split2.Length)
                return -99;

            for (int i = 0; i < split1.Length; i++)
            {
                if (Int32.Parse(split1[i]) > Int32.Parse(split2[i]))
                    return 1;

                if (Int32.Parse(split1[i]) < Int32.Parse(split2[i]))
                    return -1;
            }

            return 0;
        }
        catch
        {
            return -99;
        }
    }

如果第一个字符串从左到右更大,则返回 1,如果字符串 2,则返回 -1,如果相等则返回 0,错误则返回 -99。

所以会返回 1

string str1 = "11.30.42.29.66";
string str2 = "11.30.30.10.88";
于 2013-07-25T15:53:45.903 回答