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

荒凉一梦 提交于 2019-12-28 04:08:10

问题


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


回答1:


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.




回答2:


The Equals call scales better, as it's one string operation instead of three.

You get the best performance for case insensetive comparison with the StringComparison.OrdinalIgnoreCase option. However, as it doesn't consider cultural differences it might not always give the result that you want.

If you want to change the case for comparison, it's recommended that you use ToUpper rather than ToLower. Some exotic letters doesn't convert properly from upper to lower case, but conversion from lower to upper case works.

In most cases the performance is not crucial, so you should use the alternative that makes most sense in the situation.

You haven't specified which language you are using, but from the == operator it looks like C#. If you would use VB, you should consider that the = operator doesn't use the equality opreator of the string class, but VB's own logic for doing comparisons, which is slightly different.




回答3:


I feel more better in using second one than first one. Because, the second type will be supported in all languages and it will be more convenient to use.



来源:https://stackoverflow.com/questions/1660192/string-comparison-stra-tolower-strb-tolower-or-stra-equalsstrb-stringcom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!