문제

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?

도움이 되었습니까?

해결책

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 ß.

다른 팁

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

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

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.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top