Sandra K Sandra K - 3 months ago 4
C# Question

Why my string.Remove() is not working as expected?

I am trying to solve this problem of finding if two words are anagrams of one another (if we rearrange a string, it matches second string).

Based on Remove single character from a string I built my own function:

public class AreAnagrams
{
public static bool AreStringsAnagrams(string FirstString, string SecondString)
{
if (FirstString == null || b == null)
return false;

if (FirstString.Length != SecondString.Length)
return false;

for (int i = 0; i < SecondString.Length; i++)
{
if (FirstString.IndexOf(SecondString[i]) == -1)
return false;
else
FirstString.Remove(FirstString.IndexOf(SecondString[i]), 1); // Here it does not modify FirstString, even if I put 2nd parameter as 1
}

if (FirstString.Length > 0)
return false;

return true;
}

public static void Main(string[] args)
{
Console.WriteLine(AreStringsAnagrams("neural", "unreal"));
}
}


On my watch I see
FirstString
still as is. What is the problem? Please and thank you

Answer

Assign the result to FirstString

FirstString = FirstString.Remove(FirstString.IndexOf(SecondString[i]), 1);