Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String greater than or equal code string

I'm 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");
} 
like image 563
Sneakybastardd Avatar asked Oct 02 '13 08:10

Sneakybastardd


1 Answers

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");
} 
like image 183
Tim Schmelter Avatar answered Oct 05 '22 01:10

Tim Schmelter