7

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");
} 
1
  • You mean string or string.Length? Commented Oct 2, 2013 at 8:02

1 Answer 1

26

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");
} 
Sign up to request clarification or add additional context in comments.

7 Comments

The solution is correct, of course. The way CompareTo works with strings is complex, and it uses a culture-aware comparison, and it is not simple lexicographical ordering in all cases. For example, in many .NET cultures, a dash - will be ignored. So "-12".CompareTo("10") is like "12".CompareTo("10"), it gives a positive integer (1). And "-1".CompareTo("10") like "1".CompareTo("10") is negative (-1). There might be .NET cultures where this is different, though I doubt it.
else if... seemes a bit redundant :)
I think I would make it a tryparse in case it is not a number. Then keep the else if and have an else for this exception.
@JustinHarvey: In general it's good when people suggest how to improve code. But an answer should concentrate on the essentials. Otherwise you add too much noise and OP doesnt know what he actually needs to change or what was the issue at all. If he comes back with a FormatException we can help with the int.TryParse method.
@TimSchmelter: I am not sure I agree. I think SO is a good resource of the best answers possible to peoples questions. I think the aim should be to advise people of the best way of doing things.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.