Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string comparison failure

Tags:

c#

My application is failing on a string comparison. I have put in a breakpoint and then used the intermediate window of Visual Studio and done the following experiment

subject

"<#MethodResourceObjectives​>"

subject.Contains("<#Method")

true

subject.Contains("<#MethodResource")

true

subject.Contains("<#MethodResourceObjectives")

true

subject.Contains("<#MethodResourceObjectives>")

false

This would seem to be impossible, has anyone got a clue what could be happening?

like image 365
joe Avatar asked Jan 06 '15 10:01

joe


2 Answers

It sounds like there may well be an unprintable character between the "s" and the ">".

I usually use something like this to show the true contents of a string:

for (int i = 0; i < text.Length; i++)
{
    Console.WriteLine("{0:x4}", (int) text[i]);
}

That's not as convenient from an immediate window, of course :(

In fact, just copying and pasting your text into my Unicode Explorer (at the bottom of the page), it looks like this is indeed the problem - you've got a U+200B (zero width space) before the >. You need to work out where that's coming from.

like image 95
Jon Skeet Avatar answered Nov 15 '22 06:11

Jon Skeet


Doing a copy/paste of the text, I can confirm the same behavior.

Output:

"<#MethodResourceObjectives>".ToCharArray()
{char[27]}
    [0]: 60 '<'
    [1]: 35 '#'
    [2]: 77 'M'
    [3]: 101 'e'
    [4]: 116 't'
    [5]: 104 'h'
    [6]: 111 'o'
    [7]: 100 'd'
    [8]: 82 'R'
    [9]: 101 'e'
    [10]: 115 's'
    [11]: 111 'o'
    [12]: 117 'u'
    [13]: 114 'r'
    [14]: 99 'c'
    [15]: 101 'e'
    [16]: 79 'O'
    [17]: 98 'b'
    [18]: 106 'j'
    [19]: 101 'e'
    [20]: 99 'c'
    [21]: 116 't'
    [22]: 105 'i'
    [23]: 118 'v'
    [24]: 101 'e'
    [25]: 115 's'
    [26]: 62 '>'

Then

subject.ToCharArray()
{char[28]}
    [0]: 60 '<'
    [1]: 35 '#'
    [2]: 77 'M'
    [3]: 101 'e'
    [4]: 116 't'
    [5]: 104 'h'
    [6]: 111 'o'
    [7]: 100 'd'
    [8]: 82 'R'
    [9]: 101 'e'
    [10]: 115 's'
    [11]: 111 'o'
    [12]: 117 'u'
    [13]: 114 'r'
    [14]: 99 'c'
    [15]: 101 'e'
    [16]: 79 'O'
    [17]: 98 'b'
    [18]: 106 'j'
    [19]: 101 'e'
    [20]: 99 'c'
    [21]: 116 't'
    [22]: 105 'i'
    [23]: 118 'v'
    [24]: 101 'e'
    [25]: 115 's'
    [26]: 8203 '​'  <--------- input string contains 'garbage'
    [27]: 62 '>'
like image 44
leppie Avatar answered Nov 15 '22 05:11

leppie