I tried a challenge on edabit.com It is about "strangepairs". So the task is to return true if "The 1st string's first letter = 2nd string's last letter. The 1st string's last letter = 2nd string's first letter." ...also return true if both strings are null.
Who can spot the difference? Thanks in advance.
My Attempt:
public class Program
{
public static bool IsStrangePair(string str1, string str2)
{
if (str1[0] == str2[str2.Length - 1] && str2[0] == str1[str1.Length - 1])
return true;
if (str1 == "" && str1 == str2)
return true;
return false;
}
}
Their answer:
using System.Linq;
public class Program
{
public static bool IsStrangePair(string str1, string str2)
{
if(string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))
{
return str1 == str2;
}
return str1.First() == str2.Last()
&& str2.First() == str1.Last();
}
}
I can't spot the difference. Can someone please tell me why my solution produces an IndexOutOfRangeException and theirs doesn't? My solution works overall, all but for 2 cases. Sadly I can't see what the cases are, and I don't understand under which circumstances would produce this error.
null
strings. You also need to put your null and empty checks at the beginning. Afterwards, if the strings are not null or empty you can try and access the first and last characters. Right now, if the string is empty you are still trying to access characters that are not there hence the index out of range error.