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

后端 未结 8 1134
滥情空心
滥情空心 2020-12-16 11:07

I want to get the first place where 2 string vary from each other. example: for these two strings: \"AAAB\" \"AAAAC\"

I want to get the result 4.

How do i d

8条回答
  •  不思量自难忘°
    2020-12-16 11:54

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

提交回复
热议问题