How to compare characters in C#

Viewed 1333

I'm trying to compare two characters in C#. The "==" operator does not work for strings, you have to use the .Equals() method. In the following code example I want to read each character in the input string, and output another string without spaces.

    string inputName, outputName = null;
    // read input name from file
    foreach (char indexChar in inputName)
    {
       if (!indexChar.Equals(" "))
          outputName += indexChar;
    }

This does not work, the comparison always equals false, even when the input name has embedded spaces. I also tried using the overload method Equals(string, string), which did not work either. I'm assuming C# treats char variables as a string of length 1. Microsoft's documentation doesn't seem to mention comparing characters. Does anyone have a better method for comparing characters in a string?

3 Answers

" " is a string of length one; a char and a string never match; you want ' ', the space character:

if (indexChar != ' ')

However, if you're just trying to remove all spaces, it is probably easier to just do:

var outputName = inputName.Replace(" ", "");

This avoids allocating lots of intermediate strings.

Note also that the space character isn't the only whitespace character in unicode. If you need to deal with all whitespace characters, a regex may be a better option:

var outputName = Regex.Replace(inputName, @"\s", "");

You can use .CompareTo(char) to compare characters. Example :

if('Z'.CompareTo('Z') == 0)
   Console.WriteLine("Same character !");

Thanks for all the great suggestions. inputName.CompareTo(" ") is not the way to go for this example, you would still have to have a loop. I ended up using:

var outputName = Regex.Replace(inputName, @"\s", "")
which works, and it's only one line of code!

Related