3

Good day for all ;) Can anyone help me to find algorithms or already resolved solutions for comparing strings like SQL do it.

For instance In SQL I can compare strings for

= or <=, >, < e.t.c.

In C# as known we can't do it.

I want to compare something like

"aa" > "b" "ab" < "aa" "abc" >= "bca" and so on..

Also, maybe someone knows by what logic SQL does it?

1
  • 1
    Can u please describe more? Commented May 26, 2016 at 7:41

2 Answers 2

7

Strings implement IComparable, so you can use CompareTo.

void Main()
{
    if ("a".CompareTo("b") < 0)
    {
        Console.WriteLine("A is less than B");
    }

    if ("a".CompareTo("b") <= 0)
    {
        Console.WriteLine("A is less than or equal to B");
    }

    if ("a".CompareTo("a") == 0)
    {
        Console.WriteLine("A equals A");
    }

    if ("c".CompareTo("b") > 0) 
    {
        Console.WriteLine("C is greater than B");
    }

    if ("c".CompareTo("b") >= 0) 
    {
        Console.WriteLine("C is greater than or equal to B");
    }
}

However, if you want case-insensitive comparison then you will need to use the overload of string.Compare that allows you to ignore case. The logic is the same though.

Sign up to request clarification or add additional context in comments.

2 Comments

There's a flaw in such comparison: what if left argument is null? null.CompareTo(...) throws an exception.
@DmitryBychenko Well, yes - error checking and defensive programming is left to the implementor. That's hardly a flaw in the code I've posted!
3

Well, "aa" < "ab" equals to

  bool result = String.Compare("aa", "ab") < 0;

and so on:

 // "abc" >= "bca" 
 bool result = String.Compare("abc", "bca") >= 0;

the general pattern for "left" <=> "right" is

 String.Compare("left", "right") <=> 0

since String.Compare(left, right) returns

  • negative value (say, -123) when left < right
  • zero when left == right
  • postivie value (e.g. 789) when 'left > right'

2 Comments

@Kernighan: Compare(left, right) returns positive value (> 0) if left greater than right, it returns zero if left equals to right, and negative value when left less than right.
Thank you, i understood.

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.