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开发者_StackOverflow社区 do it in C#?
.NET 4:
string a1 = "AAAB";
string a2 = "AAAAC";
int index = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count() + 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;
}
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 <Math.Min(s1.Length, s2.Length); i++)
if (s1[i] != s2[i])
return i;
return -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();
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++;
}
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.
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.
精彩评论