Search code examples
c#asp.netends-with

What's wrong with my usage of String.EndsWith?


I can't figure out why EndsWith is returning false.

I have the C# code:

string heading = "yakobusho";
bool test = (heading == "yakobusho");
bool back = heading.EndsWith("​sho");
bool front = heading.StartsWith("yak");
bool other = "yakobusho".EndsWith("sho");
Debug.WriteLine("heading = " + heading);
Debug.WriteLine("test = " + test.ToString());
Debug.WriteLine("back = " + back.ToString());
Debug.WriteLine("front = " + front.ToString());
Debug.WriteLine("other = " + other.ToString());

The output is:

heading = yakobusho
test = True
back = False
front = True
other = True

What is going on with EndsWith?


Solution

  • The "​sho" string in the third line starts with a zero length space. "​sho".Length returns 4 while ((int)"​sho"[0]) returns 8203, the Unicode value of the zero length space.

    You can type it in a string using its hex code, eg :

    "\x200Bsho"
    

    Annoyingly, that character isn't considered whitespace so it can't be removed with String.Trim().