Is it more common/standard to compare uppercase or lowercase?
Asked Answered
S

4

8

I'm in my first six months of programming on the job and I'm still getting a feeling for standards and best practices.

When performing string or char comparison, is it more common to use ToUpper to compare uppercase characters or ToLower for lowercase? I've probably seen uppercase more often, but I was looking for a more definitive answer and maybe a long-winded optimization explanation (lower ASCII code, whatever).

Aside: In my current task, I'm using string#replace and my new string is going to be lowercase for readability, but does that necessarily mean I should use ToLower on both my source string and the substring that I'm looking for?

Skimp answered 25/7, 2013 at 14:5 Comment(0)
V
10

If there's a way to do a case-insensitive comparison without changing case you should use it instead. If not, in most situations it's better to convert to upper case. For example the German sharp-s ß converts to a double S in uppercase, and correctly compares equal to SS. If you converted to lower case this would fail since SS in lower case is ss, not ß.

Vincenza answered 25/7, 2013 at 14:15 Comment(1)
That is not true anymore. ß is regarded as lowercase and ẞ as uppercase character. Maybe you can provide another example for your recommendation? Best, MarkusTincture
N
3

Depends on which programming language you are using, C# has a case insesitive compare built-in:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
Nabob answered 25/7, 2013 at 14:7 Comment(1)
I do happen to be using C#, but I was interested in an agnostic preference when forced to use absolute casing, if one exists.Skimp
G
1

This is probably something specific to your particular development team. It should be effectively equivalent either way since all lower->upper conversions should contain a reciprocal upper->lower.

However it's probably a good idea to be consistent within a project just in case you get an oddball extended character where there is not a reciprocal relationship.

Greco answered 25/7, 2013 at 14:7 Comment(2)
Is there a situation where not being consistent would cause a problem with extended characters?Skimp
As @Vincenza points out, ß does not possess a reciprocal upper->lower as lower->upper. If you do both to-upper comparison and to-lower comparison in the same project, you may get inconsistent results.Greco
T
1

In some situations You should use: InvariantCultureIgnoreCase

string.Equals(a, b, StringComparison.InvariantCultureIgnoreCase);

Well that's my interpretation of Scott Hanselmans article. Update on the dasBlog Turkish-I bug and a reminder to me on Globalization

Toil answered 28/7, 2013 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.