Comparing strings and get the first place where they vary from eachother

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

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

static void Main(string[] args)
{
    Console.WriteLine("enter s1 :");
    string s1 = Console.ReadLine();
    Console.WriteLine("enter s2 :");
    string s2 = Console.ReadLine();

    Console.WriteLine("note: zero means there is *no* first dif index starting from s1 ");    
    Console.WriteLine("first dif index of s1 :{0}", findFirstDifIndex(s1, s2)+1);
}

private static int findFirstDifIndex(string s1, string s2)
{
    for (int i = 0; i <Math.Min(s1.Length, s2.Length); i++)
        if (s1[i] != s2[i]) 
            return i;

    return -1;
}

.NET 4:

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

int index = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count() + 1;

Tags:

C#

String