C# String greater than or equal code string

痞子三分冷 提交于 2019-12-12 10:59:43

问题


// Hello, Im trying to get my code working my comparing if a string is bigger or less than 10, but it doesn't work correctly. It writes 10 or more even if the value is less than 10.

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

回答1:


A string is not a number, so you're comparing lexicographically(from left to right). String.CompareTo is used for ordering, but note that "10" is "lower" than "2" since the char 1 is already lower than the char 2.

I assume what you want want is to convert it to an int:

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

Note that you should use int.TryParse if string1 could have an invalid format. On that way you prevent an exception at int.Parse, e.g.:

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
}

However, if you instead want to check if a string is longer or shorter than 10 characters, you have to use it's Length property:

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


来源:https://stackoverflow.com/questions/19132435/c-sharp-string-greater-than-or-equal-code-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!