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");
}
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With