简体   繁体   English

C#比较字符串中的字符

[英]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". 我正在尝试比较两个字符串中的字符,并获得最先出现的字符串,例如“ camera”比“ car”先。 but if "camera" was the second parameter, my program tells me, car comes first. 但是如果“ camera”是第二个参数,我的程序会告诉我,car优先。

     static string CompareChars(string a, string b)
    {

        foreach (char aa in a)
        {

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

        return b;

    }

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. 你比较的第一个字母a与所有的信件从b ,而不是比较的第一个字母a仅为第一个字母b和移动到这两个字符串的第二个字母。

What you probably want is a single for loop + indexing into both strings. 您可能想要的是一个for循环+到两个字符串的索引。

Or you can use built-in comparison function: 或者您可以使用内置的比较功能:

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

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"; 如第一个答案所述,您正在将第一个字符串中的所有字符与第二个字符串中的每个字母进行比较,因此,将其分解就可以说您有这个: var a = "this"; var b = "that"; 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://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-compare-strings https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/strings/how-to-compare-strings

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM