比较两个字符串忽略大小写的最佳方法

俊志

我想比较两个不区分大小写的字符串,但是我不确定执行此操作的最佳方法。琴弦的平均长度为20,这个问题更多地与现有技术有关,而不与最佳性能有关。

我大部分的代码使用

bool output = "foo".ToLower() == "FOO".ToLower();

在我看来,这有点过时了。我见过很多次的另一种方式是

bool output = Regex.IsMatch("foo", "FOO", RegexOptions.IgnoreCase);

我想这是可能的,但是RegEx并不是为如此简单的事情而设计的。

之后,剩下3种“好”方式:

bool output = string.Compare("foo", "FOO", StringComparison.CurrentCultureIgnoreCase) == 0;
bool output = string.Compare("foo", "FOO", true) == 0;
bool output = "foo".Equals("FOO", StringComparison.CurrentCultureIgnoreCase);
德米特里·拜琴科(Dmitry Bychenko)

如果您查看相应的参考资料

https://referencesource.microsoft.com/#mscorlib/system/string.cs,bda3b2c94b5251ce

    public static int Compare(String strA, String strB, bool ignoreCase)
    {
        if (ignoreCase) {
            return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
        }
        return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
    }

https://referencesource.microsoft.com/#mscorlib/system/string.cs,0be9474bc8e160b6

    public static int Compare(String strA, String strB, StringComparison comparisonType) 
    {
    ... 
        // Agrument validation, reference equality, null test

        switch (comparisonType) {
        ...
           case StringComparison.CurrentCultureIgnoreCase:
                return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);

https://referencesource.microsoft.com/#mscorlib/system/string.cs,d47c1f57ad1e1e6e

    public static bool Equals(String a, String b, StringComparison comparisonType) {
    ... 
       // Agrument validation, reference equality, null test

       switch (comparisonType) {
        ...
           case StringComparison.CurrentCultureIgnoreCase:
                return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);

您会发现这三种方法彼此相等至于其他方式,Regex.IsMatch绝对是过冲(您要做的就是比较字符串);ToLower()在处理文化特定字母时可能会很棘手,请参阅

https://zh.wikipedia.org/wiki/点缀_无点_I

这就是为什么更好的设计是清楚地声明您的意图(=我想比较字符串)然后屏蔽它们(然后让系统欺骗您)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

比较两个字符串,忽略C#中的大小写

确保两个字符串不相等并忽略大小写

如何比较两个字符串忽略Swift语言中的大小写?

在 C++ 中比较两个字符串时如何忽略文本大小写?

如何比较Clojure中两个字符串的大小写?

比较不区分大小写的两个字符串

如何比较两个字符串的大小写和变音符号不敏感?

在MySQL中区分大小写的两个字符串

如何比较忽略大小写的字符串

有没有办法比较两个字符串,没有它是区分大小写?

Perl6 cmp的两个字符串可以区分大小写吗?

文件中两个字符串之间不区分大小写的搜索

将字符串与字符串数组进行比较,忽略大小写

如何在排序和忽略大小写的同时保留两个“相等”字符串的行顺序?

替换字符串并忽略大小写Python

字符串包含-忽略大小写

在忽略大小写的情况下比较字符串的有效方法是什么?

如何从需要相互比较的两个字符中检测字母及其大小写格式?

Java流排序与字符串比较忽略大小写

在哈希图中比较字符串与键值时忽略大小写

如何在Java中比较忽略大小写的字符串

C# 字符串比较忽略大小写敏感 HTML 标签

如何在字符串比较中忽略大小写

角度2/4字符串比较(忽略大小写)

比较两个字符串,忽略空格、换行、换行

比较两个字符串并忽略(但不能替换)重音。的PHP

如何返回任意两个字母之间的最大距离(以az忽略大小写)?

比较两个字符串时间

Powershell比较两个字符串