Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - String comparison - strA.ToLower()==strB.ToLower() or strA.Equals(strB,StringComparisonType)?

As per title, what practise for string comparisons do you use and why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You haven't specified a platform, but I'm guessing .NET. I would strongly suggest you use the latter form - because case comparisons aren't as simple as you might expect. (It also avoids creating extra strings, but that's a different matter.)

For example, what do you want your code to do when presented with "mail" and "MAIL" when it's running in Turkey? If you use ToLower it will return false, and likewise if you use CurrentCultureIgnoreCase - but if you use InvariantCultureIgnoreCase it will return true. You need to think about the source of the data and what you're trying achieve with it.

See the recommendations for using strings in MSDN for more information and guidance.

Aside from anything else, I'd say that the latter expresses your intent more effectively. You're not actually interested in the lower case values of the strings - you're interested in equality in a case-insensitive way... which is exactly what the second form expresses.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...