I have a program that returns the distance from an ASCII table of two mismatched characters that are at the same position in two strings. I would like to shorten my program, but in such a way that it returns the same result as before.(The program cannot return negative values, so it checks in each If instruction which number has the greater value and strings always have the same length) Now program throws an error every time when comparing: "System.IndexOutOfRangeException: 'Index was outside the bounds of the array." but it displays the correct result ..
Code
public static void incompatible(string a, string b)
{
char[] characters1 = new char[a.Length];
char[] characters2 = new char[b.Length];
for (int i = 0; i < a.Length; i++)
{
characters1 [i] = a[i];
}
for (int i = 0; i < b.Length; i++)
{
characters2 [i] = b[i];
}
if (a.Length >= 0 || b.Length >= 0)
{
if (characters1 [0] != characters2 [0])
{
if (characters1 [0] > characters2 [0])
{
Console.WriteLine(characters1 [0] - characters2 [0]);
}
else if (characters1 [0] < characters2 [0])
{
Console.WriteLine(characters2 [0] - characters1 [0]);
}
}
}
if (a.Length >= 1 || b.Length >= 1)
{
if (characters1 [1] != characters2 [1])
{
if (characters1 [1] > characters2 [1])
{
Console.WriteLine(characters1 [1] - characters2 [1]);
}
else if (characters1 [1] < characters2 [1])
{
Console.WriteLine(characters2 [1] - characters1 [1]);
}
}
}
if (a.Length >= 2 || b.Length >= 2)
{
if (characters1 [2] != characters2 [2])
{
if (characters1 [2] > characters2 [2])
{
Console.WriteLine(characters1 [2] - characters2 [2]);
}
else if (characters1 [2] < characters2 [2])
{
Console.WriteLine(characters2 [2] - characters1 [2]);
}
}
}
if (a.Length >= 3 || b.Length >= 3)
{
if (characters1 [3] != characters2 [3])
{
if (characters1 [3] > characters2 [3])
{
Console.WriteLine(characters1 [3] - characters2 [3]);
}
else if (characters1 [3] < characters2 [3])
{
Console.WriteLine(characters2 [3] - characters1 [3]);
}
}
}
I have now fourteen If instructions like those above.