Case Insensitive String Comparison?

J

jpuopolo

All:

The String class has a CompareTo method, that compares to strings. Is there
a similar method that performs case-insensitive comparisons?

Thanks,
John
 
J

Jon Skeet [C# MVP]

jpuopolo said:
The String class has a CompareTo method, that compares to strings. Is there
a similar method that performs case-insensitive comparisons?

In 2.0 there are overloads of Compare which take a StringComparison,
allowing you to specify case- or culture-insensitive comparisons.
 
P

Peter K

The String class has a CompareTo method, that compares to strings. Is
there a similar method that performs case-insensitive comparisons?

If you can't use the other suggestions you could try to convert both
strings to upper or lower case before comparing them.
 
J

Jon Skeet [C# MVP]

If you can't use the other suggestions you could try to convert both
strings to upper or lower case before comparing them.

You need to be *very* careful with that, and consider which culture
you want to use when upper/lower-casing. You might think that
"mail".ToUpper() will give "MAIL" - but it doesn't in Turkey...

Jon
 
P

Peter K

You need to be *very* careful with that, and consider which culture
you want to use when upper/lower-casing. You might think that
"mail".ToUpper() will give "MAIL" - but it doesn't in Turkey...

Thanks. My programs have always either been with English or Danish texts so
I've never seen that problem with ToUpper or ToLower. What do you do when
you use ToUpper then - always ensure that the culture is set to something
you know so you know what "uppercase" means?
 
J

jpuopolo

All:

The String class has a CompareTo method, that compares to strings. Is there
a similar method that performs case-insensitive comparisons?

Thanks,
John


I used String.Compare() and it worked well.

Thanks, all....
 
J

Jon Skeet [C# MVP]

Peter K said:
Thanks. My programs have always either been with English or Danish texts so
I've never seen that problem with ToUpper or ToLower. What do you do when
you use ToUpper then - always ensure that the culture is set to something
you know so you know what "uppercase" means?

If you're using it for case-insensitive comparisons, you should specify
CultureInfo.InvariantCulture, or use ToUpperInvariant or
ToLowerInvariant.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top