C# string.IndexOf() returns unexpected value
c#, indexof, string
Solution
I believe you already have the answer using an ordinal search
int i = s.IndexOf(" ", StringComparison.Ordinal);
You can read a small section in the documentation for the String Class which has this to say on the subject:
String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the IndexOf method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to Empty and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case.
Problem
This question applies to C#, .net Compact Framework 2 and Windows CE 5 devices. I encountered a bug in a .net DLL which was in use on very different CE devices for years, without showing any problems. Suddenly, on a new Windows CE 5.0 device, this bug appeared in the following code: ``` string s = "Print revenue receipt"; // has only single space chars int i = s.IndexOf(" "); // two space chars ``` I expect i to be -1, however this was only true until today, when indexOf suddenly returned 5. Since this behaviour doesn't occur when using ``` int i = s.IndexOf(" ", StringComparison.Ordinal); ``` , I'm quite sure that this is a culture based phenomenom, but I can't recognize the difference this new device makes. It is a mostly identical version of a known device (just a faster cpu and new board). Both devices: - run Windows CE 5.0 with identical localization - System.Environment.Version reports '2.0.7045.0' - CultureInfo.CurrentUICulture and CultureInfo.CurrentCulture report 'en-GB' (also tested with 'de-DE') - 'all' related registry keys are equal. The new device had the CF 3.5 preinstalled, whose GAC files I experimentally renamed, with no change in the described behaviour. Since at runtime always Version 2.0.7045.0 is reported, I assume these assemblies have no effect. Although this is not difficult to fix, i can not stand it when things seem that magical. Any hints what i was missing? Edit: it is getting stranger and stranger, see screenshot: One more: