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

后端 未结 8 1098
滥情空心
滥情空心 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 12:03
    int index;
    int len = Math.Min(string1.Length, string2.Length);
    for (index = 0; index < len; index++)
        if (string1[index] != string2[index])
            break;
    

    This would provide "3" for your example (zero-based indexing), so just increment the result by one.

    0 讨论(0)
  • 2020-12-16 12:07
    string one = "AAAB";
    string two = "AAAAC";
    
    int found = -1;
    int index = 0;
    while (one != two && found == -1 && one.Length > index && two.Length > index)
    {
        if (one[index] != two[index]) found = index;
        index++;
    }
    
    0 讨论(0)
提交回复
热议问题