27

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 do it in C#?

Adibe7
  • 3,469
  • 7
  • 30
  • 36
  • 7
    Sounds like a job for a good-old for loop. – moinudin Jan 03 '11 at 15:57
  • 4
    @marco: Yes, but I'm waiting for the LINQ solutions. – H H Jan 03 '11 at 15:59
  • 5
    For reference, if you want to be consistent with the rest of the language, the position would be 3 (not 4). In just about all C'ish languages, strings' char indexes are 0-based. – cHao Jan 03 '11 at 16:14

8 Answers8

40

.NET 4:

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

int index = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count() + 1;
Ohad Schneider
  • 36,600
  • 15
  • 168
  • 198
18
    /// <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;
    }
Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
Jay
  • 56,361
  • 10
  • 99
  • 123
9
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;
}
Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
  • If you were to return when the chars weren't equal you could just return -1 in the end of the function and avoid the overhead of another full-string compare. – jakobbotsch Jan 03 '11 at 18:25
  • There are several mistakes in this code. Easily corrected, but still mistakes (length should be Length; in the for loop the iterator is named "index" but then you refer to it only as "i") – Pavel Matuska Oct 06 '12 at 20:49
3
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;
}
Greg
  • 2,163
  • 1
  • 21
  • 23
Iman
  • 17,932
  • 6
  • 80
  • 90
1

You can create an extension method to do the trick:

public static class StringExtensions {
    public static int IndexOfDifferenceFrom(this string source, string compareTo)
    {
        for(var i = 0; i < source.Length && i < compareTo.Length; ++i) {
            if (source[i] != compareTo[i]) {
                return i;
            }
        }

        return source.Length < compareTo.Length ? source.Length : compareTo.Length;
    }

}

Or, for a LINQy solution:

var index = string1.Where((ch, i) => string2[i] == ch).Select((ch, i) => i).DefaultIfEmpty(-1).First();
Jon
  • 428,835
  • 81
  • 738
  • 806
1
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++;
}
Greg
  • 2,163
  • 1
  • 21
  • 23
hunter
  • 62,308
  • 19
  • 113
  • 113
0
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.

Greg
  • 2,163
  • 1
  • 21
  • 23
Sapph
  • 6,118
  • 1
  • 29
  • 32
0
int compare( String a, String b ){

   for( int i = 0; i < min( a.length, b.length ); i++ ){

      if( a.getCharAt(i) != b.getCharAt(i) ){
         return i;
      }

  }

  return -1; //a contained in b, or b contained in a

} 

The code above doesn't check anything like nulls, etc.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510