André
André

Reputation: 37

C# comparing chars from strings

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;

    }

Upvotes: 1

Views: 1984

Answers (2)

Mark Davies
Mark Davies

Reputation: 1497

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

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

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;
}

Upvotes: 3

Related Questions