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

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

我想得到结果4。

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

.NET 4:

string a1 = "AAAB"; string a2 = "AAAAC"; int index = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count() + 1; 
  ///  /// Compare two strings and return the index of the first difference. Return -1 if the strings are equal. ///  ///  ///  ///  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; } 
 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; } 
 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  
 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++; } 

将字符串数组中的字符串分解为CharArray并循环遍历它,一次检查一个字符。

您可以创建一个扩展方法来执行此操作:

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

或者,对于LINQy解决方案:

 var index = string1.Where((ch, i) => string2[i] == ch).Select((ch, i) => i).DefaultIfEmpty(-1).First(); 
 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 } 

上面的代码不检查任何像nulls等的东西。

 int index; int len = Math.Min(string1.Length, string2.Length); for (index = 0; index < len; index++) if (string1[index] != string2[index]) break; 

这将为您的示例提供“3”(从零开始的索引),因此只需将结果递增1。