C#字符串大于或等于代码字符串

时间:2013-10-02 08:00:56

标签: c# string string-comparison

//你好,我试图让我的代码工作我的比较如果一个字符串更大或小于10,但它无法正常工作。即使该值小于10,它也会写入10或更多。

int result = string1.CompareTo("10");
if (result < 0)
{
     Console.WriteLine("less than 10");
}
else if (result >= 0)
{
     Console.WriteLine("10 or more");
} 

1 个答案:

答案 0 :(得分:21)

字符串不是数字,因此您要按字典顺序(从左到右)进行比较。 String.CompareTo用于排序,但请注意"10"“低于"2",因为字符1已经低于而不是2 {1}}。

我认为您想要的是将其转换为int

int i1 = int.Parse(string1);
if (i1 < 10)
{
    Console.WriteLine("less than 10");
}
else if (i1 >= 10)
{
    Console.WriteLine("10 or more");
} 

请注意,如果string1格式无效,则应使用int.TryParse。这样就可以防止int.Parse发生异常,例如:

int i1;
if(!int.TryParse(string1, out i1))
{
    Console.WriteLine("Please provide a valid integer!");
}
else
{
    // code like above, i1 is the parsed int-value now
}

但是,如果您想要检查字符串更长更短是否超过10个字符,则必须使用它的Length属性:

if (string1.Length < 10)
{
    Console.WriteLine("less than 10");
}
else if (string1.Length >= 10)
{
    Console.WriteLine("10 or more");
}