Search code examples
c#.netindexoflastindexofinvariantculture

.NET CultureInfo.InvariantCulture.CompareInfo IndexOf vs LastIndexOf - What is going on?


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?


Solution

  • 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