int n = string.numDifferences("noob", "newb"); // 2
??
int n = string.numDifferences("noob", "newb"); // 2
??
Take a look at one of the methods for measuring edit distance.
import math
def differences(s1, s2):
count = 0
for i in range(len(s1)):
count += int(s1[i] != s2[1])
# count += math.sqrt( (len(s1) - len(s2)) **2) #add this line if the two strings are of different length and differences counts the how many characters one string has more than the other.
return count
Hope this helps
Assuming that you only want to compare characters at the same indices, the following C# solution (using methods provided by LINQ) should do the trick:
var count = s1.Zip(s2, (c1, c2) => c1 == c2 ? 0 : 1).Sum();
This "zips" the two strings, and then returns 0 for each index where the characters are the same and 1 for each index where they differ. Then we simply sum the numbers and we get the result.
I would perhaps do this as an extension method (C# code)
static class StringExtensions
{
public static int NumberOfDifferences(this string input, string other)
{
// difference in lengths is initial difference value
int difference = Math.Abs(input.Length - other.Length);
for (int i = 0; i < Math.Min(input.Length, other.Length); i++)
{
if (input[i] != other[i])
difference++;
}
return difference;
}
}
You could call it like
"blah".NumberOfDifferences("foo");
The number you are trying to find is called the edit distance. Wikipedia lists several algorithms you might want to use; the Hamming distance is a very common way of finding the edit difference between two strings of the same length (it's often used in error-correcting codes); the Levenshtein distance is similar, but also takes insertions and deletions into account. Wikipedia, of course, lists several others (e.g. Damerau-Levenshtein distance, which includes transpositions); I don't know which you want, as I'm no expert and the choice is domain-specific. One of these, though, should do the trick.
You already got excellent answers if you mean "edit distance". If you just mean "number of characters that differ" (for two strings of the same length), in Python, the simplest approach would be:
sum(c1!=c2 for c1, c2 in zip(s1, s2))
and if you also want to add the length difference, append
+ abs(len(s1) - len(s2))
Of course, if you do want edit distances, this approach would be far too simplistic;-).