When i run following code in .Net Core 3.1
i get 6
//Net Core 3.1
string s = "Hello\\r\\nwor
The comments and @Ray's answer contain the reason.
And though hacking the .csproj
or runtimeconfig.json
file may save your day the real solution is to specify the comparison explicitly:
// this returns the expected result
int idx = s.IndexOf("\n", StringComparison.Ordinal);
For some reason IndexOf(string)
defaults to use current culture comparison, which can cause surprises even with earlier .NET versions when your app is executed in an environment that has different regional settings than yours.
Using a culture-specific search is actually a very rare scenario (can be valid in a browser, book reader or UI search, for example) and it is much slower than ordinal search.
The same issue applies for StartsWith
/EndsWith
/Contains
/ToUpper
/ToLower
and even ToString
and Parse
methods of formattable types (especially when using floating-point types) as these also use the current culture by default, which can be the source of many gotchas. But recent code analyzers (eg. FxCop, ReSharper) can warn you if you don't use a specific comparison or culture. It is recommended to set a high severity for these issues in a product code.