Why am I seeing this unexpected behavior in .NET StartsWith?

It must be a .NET error, right?

"KonNy".StartsWith("Kon") returns false, and "KonNy".StartsWith("Ko") and "KonN".StartsWith("Kon") returns true.

Is there anything that I am missing here?

+7
source share
3 answers

Repeat from comments:

I do not know .NET specifically, but I suspected that you could observe this phenomenon if StartsWith followed the sort, where nny was a single letter, such as Hungarian. If I am right, and if you change your mapping to neutral, your β€œmistake” will disappear. :)

+14
source

EDIT: This is a culture sensitivity problem that only appears in Hungarian cultures. Repro:

 using System; using System.Globalization; class Test { static void Main() { foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)) { if (!"KonNy".StartsWith("Kon", false, culture)) { Console.WriteLine(culture); } } } } 

Output:

 hu hu-HU 

If you want a comparison with culture insensitivity, specify StringComparison.Ordinal as the response to the request.

+9
source

I suspect your string has multiple characters in it with zero width or non-printable. The Unicode character space contains some unpleasant, unintuitive surprises. Try calling ToCharArray in string literals and checking the received char codes.

And try calling StartWith with StringComparison.Ordinal so your culture doesn't get in the way.

+1
source

All Articles