1

Why my code just compare first character? Where's my error? I'am trying to compare the characters from two strings and get the string which comes first like "camera" comes first than "car". but if "camera" was the second parameter, my program tells me, car comes first.

     static string CompareChars(string a, string b)
    {

        foreach (char aa in a)
        {

            foreach (char bb in b)
            {
                if (aa > bb)
                    return a;
            }
        }

        return b;

    }
1
  • The debugger at your fingertips is a great way to figure this sort of thing out for yourself...and learn more about how your code actually executes. Commented Jan 20, 2018 at 18:27

2 Answers 2

3

You're comparing the first letter of a with all the letters from b instead of comparing first letter of a with only first letter of b and moving on to second letters of both strings.

What you probably want is a single for loop + indexing into both strings.

Or you can use built-in comparison function:

static string CompareString(string a, string b)
{
    return a.CompareTo(b) < 0 ? a : b;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, incredible . Thanks Marcin.
1

As stated in the first answer you are comparing all of the chars in the first string to each letter in the second string so, breaking this down lets say you have this: var a = "this"; var b = "that"; You comparison set would look something like

if('t' >'t')

if('t' > 'h')

if('t' > 'a')

if('t' > 't')

if('h' > 't')

if('h' > 'h')

if('h' > 'a')

if('h' > 't')

and so on.

As stated you can use

static string CompareString(string a, string b)
{
   return a.CompareTo(b) < 0 ? a : b;
}

Here is a link to comprehensive string comparison documentation:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-compare-strings

Hope this helps

Comments

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.