Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare characters in C#

Tags:

c#

char

compare

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?

like image 937
Chris Cantwell Avatar asked Dec 10 '25 21:12

Chris Cantwell


2 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", "");
like image 116
Marc Gravell Avatar answered Dec 12 '25 09:12

Marc Gravell


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

if('Z'.CompareTo('Z') == 0)
   Console.WriteLine("Same character !");
like image 40
Xerox9000 Avatar answered Dec 12 '25 10:12

Xerox9000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!