简体   繁体   中英

How to compare text: ANSI vs Unicode

I'm trying to find a certificate by serial number. Apparently both sides are equal but debugger says they are not. What am I missing here? I noticed IDE warned me when I copied & pasted serial number into text editor, I didn't care about the message; unicode blah blah...

UPDATE

  1. I copied the serial number from certificate window.
  2. Open Notepad2 new file. It's default ANSI. Pasted the text. Copied again. Pasted into VS. Values are not equal.
  3. Set Notepad2 file as Unicode. Pasted serial number. Copied from Notepad2 and pasted into VS. Now they are equal.

It seems unicode vs ansi problem.

serial.png

I can't see anything wrong with how you create the string or how you compare it. That should work just fine. Strings in .NET are always unicode, so there is no possible encoding problem either.

Retype the serial string manually. It seems that you got some unusual characters in there when pasting it, for example non-breaking spaces instead of regular spaces.

When I copied I've selected "extra space". Weird but it doesn't appear in the IDE. If I select the serial number carefully, everything will be ok.

In Notepad it appears as below:

?00 c4 aa b9 b1 08 90 5d

It's hex 3F char (question mark) and it doesn't appear in notepad if it's unicode. In ANSI mode it becomes visible as ?

diff.png

As far as I know, comparison in UNICODE works flawlessly when English alphanumerics are used. For other languages, there are caveats.

Will you please provide "copy-able" code, so that I ca check it on my machine? (PS: I am feeling too lazy to type it..:o)

Also, note that == works only with value types. You should use EqualsTo() for comparing ref types (this way, you will be comparing values, not references!)

Instead of

operator==

you should use

string.Equals(object Obj)

method. The "==" tests for equality of the reference not contents.

See MSDN for further reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM