2

In our app I wanted to be good citizen and transfer from culture-aware string comparisons to some deterministic comparisons in InvariantCulture, but because of that my app started crashing with OutOfMemory because of infinite cycle.

It all comes down to this. I evaluated this in Immediate Window:

CultureInfo.InvariantCulture.CompareInfo.IndexOf("(např. BroadSwo", " ", 0, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace);
6

CultureInfo.InvariantCulture.CompareInfo.LastIndexOf("(např. BroadSwo", " ", 0, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace);
-1

What on earth is going on here?

How LastIndexOf can give me 'not found' when IndexOf with the same culture and same input gives me 'found some'?

Is this a BUG? Or what I am missing?

Jacob
  • 627
  • 6
  • 15

2 Answers2

3

It seems that the startIndex parameter of CultureInfo.InvariantCulture.CompareInfo.LastIndexOf needs to be the length of the string, because it searches backwards. This worked for me:

CultureInfo.InvariantCulture.CompareInfo.LastIndexOf("(např. BroadSwo", " ", 15, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace)

It returned 6 as did IndexOf.

Alastair Brown
  • 1,598
  • 8
  • 12
  • http://referencesource.microsoft.com/#mscorlib/system/globalization/compareinfo.cs#906 start index is zero-based, so it should be source.Length - 1 – Chizh Jun 29 '16 at 00:39
  • Yes I found out myself. :) As you can see in the next answer. Thank you anyway for quick response. However it is interesting, that it works with 15, because source.Length is 15 and startIndex is zero-based. So 14 should be last index. Hmm – Jacob Jun 29 '16 at 00:52
2

I was mistaken..

LastIndexOf is searching from the end of the source to the begining. So when I set startPosition = 0, then it goes from position 0 to 0 and finds nothing.

The correct call of LastIndexOf is:

CultureInfo.InvariantCulture.CompareInfo.LastIndexOf("(např. BroadSwo", " ", "(např. BroadSwo".Length - 1, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace);
6
Jacob
  • 627
  • 6
  • 15