Wednesday, June 09, 2004

Case insensitive String functions

The more I use .NET, the more I become astonished about what I still don't know. No, I'm not talking about some highly-advanced features: I'm talking about simple things, as string methods.
Sometimes you may need to do a case-insensitive IndexOf, or a case-insensitive StartsWith. Most people would call ToLower or ToUpper. This has two problems:
1. This is not the same thing than a case-insensitive search on some cultures. Second
2. This is slow, and creates two more objects to be collected. If done on a loop, this can create a lot of unnecessary overhead.

The solution most people (me included) do is creating their own case-insensitive IndexOf or StartsWith.
Until I found the CompareInfo class. You can use it through CultureInfo.CurrentCulture.CompareInfo and call, e.g.:

    CultureInfo.CurrentUICulture.CompareInfo.IndexOf(text, substring, CompareOptions.IgnoreCase)

Cool, huh?
It's very fast and doesn't add overhead to the GC.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?