比较字符串并获得彼此不同的第一个位置

Adi*_*be7 19 c# string

我想得到第一个2字符串彼此不同的地方.示例:对于这两个字符串:"AAAB""AAAAC"

我想得到结果4.

我如何在C#中做到这一点?

Oha*_*der 27

.NET 4:

string a1 = "AAAB";
string a2 = "AAAAC";

int index = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count() + 1;
Run Code Online (Sandbox Code Playgroud)

  • 为了清楚起见,我也赞成这一点,以获得创造力和乐趣.但是当OP进行大量的字符串比较时,任何for循环解决方案都会快得多. (4认同)
  • 如果出现问题,似乎总是有LINQ解决方案;) (3认同)

Jay*_*Jay 15

    /// <summary>
    /// Compare two strings and return the index of the first difference.  Return -1 if the strings are equal.
    /// </summary>
    int DiffersAtIndex(string s1, string s2)
    {
        int index = 0;
        int min = Math.Min(s1.Length, s2.Length);
        while (index < min && s1[index] == s2[index]) 
            index++;

        return (index == min && s1.Length == s2.Length) ? -1 : index;
    }
Run Code Online (Sandbox Code Playgroud)


Dan*_*lba 8

string str1 = "AAAB";
string str2 = "AAAAC";

// returns the first difference index if found, or -1 if there's
// no difference, or if one string is contained in the other
public static int GetFirstDiffIndex(string str1, string str2)
{
    if (str1 == null || str2 == null) return -1;

    int length = Math.Min(str1.Length, str2.Length);

    for (int index = 0; index < length; index++)
    {
        if (str1[index] != str2[index])
        {
            return index;
        }
    }

    return -1;
}
Run Code Online (Sandbox Code Playgroud)

  • +1用于处理它们相等的情况. (4认同)