-3

I have written a short code to check the equivalence of two scrambled string. but the code is not working as expected.

The code is given below.

        string firstString, secondString;
        Console.Write("Enter the First String: ");
        firstString = Console.ReadLine();
        Console.Write("Enter the 2nd   String: ");
        secondString = Console.ReadLine();
        char[] firstArray = firstString.ToArray();
        char[] secondArray = secondString.ToArray();           
        Array.Sort(firstArray);
        Array.Sort(secondArray);
        firstString = firstArray.ToString();
        secondString = secondArray.ToString();
        if(firstString == secondString)
        {
            Console.Write("Matched");
        }
        else 
            Console.Write("Not Matched");            
            Console.ReadKey();                        
    }        
}
  • 1
    What are the inputs that you are using? Setting breakpoints and debugging your code is the best way to trace what is happening with it along the way. – jonsca Jul 17 '18 at 23:08
  • 1
    Possible duplicate of [.NET / C# - Convert char\[\] to string](https://stackoverflow.com/questions/1324009/net-c-sharp-convert-char-to-string) – jonsca Jul 17 '18 at 23:13
  • I did it already. But still not working. If i use foreach loop to display the char of the string, every character ia sorted but uaing if else loop its not matched with another string. – Ravi Shankar Shah Jul 18 '18 at 20:19
  • Don't use a foreach loop, just use the *actual* debugger and step through it. You'll see that what the answer below says is correct, you are comparing the string of the type name versus the string of the type name, which means they are equal. – jonsca Jul 18 '18 at 22:23

1 Answers1

2
firstArray.ToString();

will return the type of array in string format. If you debug, you'll see the value of firstString will be

System.Char[]

and not the content of the array.

Therefore your string comparison will always return true.


To achieve your result, if you can use LINQ, you can use SequenceEqual like this:

Console.Write("Enter the First String: ");
var firstString = Console.ReadLine();
Console.Write("Enter the 2nd   String: ");
var secondString = Console.ReadLine();
var list1 = firstString.ToList();
var list2 = secondString.ToList();
list1.Sort();
list2.Sort();

if (list1.SequenceEqual(list2))
    Console.Write("Matched");
else
    Console.Write("Not Matched");
Sach
  • 10,091
  • 8
  • 47
  • 84
  • It most definitely is working. Here's a [Fiddle](https://dotnetfiddle.net/9FjMEU). What is the input you're using? – Sach Jul 18 '18 at 20:38