0

I have this code where I output the following four chars using Current Culture and Ordinal String Comparison types.

string str4 = "one two three";

Console.WriteLine(str4.IndexOf('\u0000', StringComparison.CurrentCulture));
Console.WriteLine(str4.IndexOf('o', StringComparison.CurrentCulture));
Console.WriteLine(str4.LastIndexOf("\u0000", StringComparison.CurrentCulture));
Console.WriteLine(str4.LastIndexOf("e", StringComparison.CurrentCulture));

Console.WriteLine();

Console.WriteLine(str4.IndexOf('\u0000', StringComparison.Ordinal));
Console.WriteLine(str4.IndexOf('o', StringComparison.Ordinal));
Console.WriteLine(str4.LastIndexOf("\u0000", StringComparison.Ordinal));
Console.WriteLine(str4.LastIndexOf("e", StringComparison.Ordinal));

From the output I can see that the string has an embedded null char at position 0 and an 'o' char at position 0 as well using the currentculture, how is this possible?

then there is an embedded null char at the position 13 (but the string has only 12 positions(0 through 12)) using the current culture, how does this work?

then when I use Ordinal

The output shows that there are NO embedded null chars either at the beginning or end of the string as the method returns -1.

Does this mean that current culture sees embedded null chars while ordinal does not?

Current output looks like:

0
0
13
12

-1
0
-1
12
Andrew
  • 721
  • 4
  • 14
Eric Movsessian
  • 488
  • 1
  • 11

1 Answers1

3

From the documentation for IndexOf:

"Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. If value consists only of one or more ignorable characters, the IndexOf(String, Int32, Int32, StringComparison) method always returns startIndex, which is the character position at which the search begins."

The zeros must be ignorable characters, therefore startIndex is returned.

Andrew
  • 721
  • 4
  • 14