im trying to learn how to get the coincidence porcentage between two base 64 strings in asp.net c#
i woul like to have
String A String B
and to get a result like this
coincidence = 80,3454
CodePudding user response:
You can compare char by char, regarding the positions of each pair of chars. Divide the number of coinside chars with the number of chars in that base64 string. You'll get the percentage.
CodePudding user response:
This assumes that both strings will be the same length. And if they're base64 then presumably they're already upper case. But you can adjust either of those requirements as needed.
public static float CoincidenceRate(string a, string b)
{
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b) || a.Length != b.Length)
{
throw new ArgumentException("Both strings must be non-null, non-empty, and the same length.");
}
float matches = 0;
for (var index = 0; index < a.Length; index )
{
if (a[index] == b[index])
{
matches ;
}
}
return matches / a.Length;
}
What if they're not the same length? You could do this:
public static float Base64CoincidenceRate(string a, string b)
{
if (a == null || b == null)
{
throw new ArgumentNullException("Neither input may be null.");
}
// prevent division by zero
if (a.Length == 0 && b.Length == 0)
{
return 0; // or throw an exception, or return 1.
}
string paddedA = a.Length >= b.Length ? a : a.PadRight(b.Length, ' ');
string paddedB = b.Length >= a.Length ? b : b.PadRight(a.Length, ' ');
float matches = 0;
for (var index = 0; index < paddedA.Length; index )
{
if (paddedA[index] == paddedB[index])
{
matches ;
}
}
return matches / paddedA.Length;
}
In this case the inputs must be base64. Otherwise if they're not the same length and the longer one contains spaces the result may be off. As long as neither contains spaces, padding the shorter one with spaces ensures that characters appended to one won't match characters in the other.
