C#使用比较函数比较字符串

时间:2019-02-20 00:00:20

标签: c#

我可能缺少明显之处,但是如何为string.Equals()提供比较功能?

我需要测试字符串是否相等,但允许首字母使用不同的大小写,因此StringComparison没什么用,但是我看不到为字符串提供自己的函数的方法。

var s1="John";
var s2="john";

if (string.Equals(s1, s2, ????)) console.Write("Equal!!");

2 个答案:

答案 0 :(得分:2)

Equals方法没有采用自定义比较功能的重载,但是您可以将其写为extension method

public static class Extensions
{
    public static bool EqualsCaseExceptFirst(this string input, string other)
    {
        if (input == null) throw new NullReferenceException();
        if (ReferenceEquals(input, other)) return true;
        if (input.Length != other.Length) return false;
        if (input.Length == 0) return true;
        if (!input.Substring(0, 1).Equals(other.Substring(0, 1), 
            StringComparison.OrdinalIgnoreCase)) return false;

        return input.Length == 1 || input.Substring(1).Equals(other.Substring(1));
    }
}

示例测试可能类似于:

private static void Main()
{
    var testStrings = new List<string>
    {
        "hello", "Hello", "HELLO", "hELLO"
    };

    var sample = "Hello";

    foreach (var testString in testStrings)
    {
        var result = sample.EqualsCaseExceptFirst(testString);
        Console.WriteLine($"'{sample}' == '{testString}'  :  {result}");
    }

    Console.WriteLine("----------");

    sample = "HELLO";

    foreach (var testString in testStrings)
    {
        var result = sample.EqualsCaseExceptFirst(testString);
        Console.WriteLine($"'{sample}' == '{testString}'  :  {result}");
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}

输出

enter image description here


您在注释中提到要创建IEqualityComparer类,因此这里有一个简单地重用此方法的示例:

class CustomComparer : IEqualityComparer<string>
{
    public bool Equals(string first, string second)
    {
        return first?.EqualsCaseExceptFirst(second) ?? false;
    }

    public int GetHashCode(string obj)
    {
        return obj?.GetHashCode() ?? 0;
    }
}

答案 1 :(得分:1)

您可以自己滚,加入胡椒粉和盐调味

  public static bool MyStringEquals(this string str1, string str2, StringComparison comparison = StringComparison.CurrentCulture)
      => !(str1?.Length > 0) || !(str2?.Length > 0) || string.Equals(str1.Substring(1), str2.Substring(1),comparison);

用法

var s1 = "asd";
var s2 = "bsd";

var result = s1.MyStringEquals(s2, StringComparison.Ordinal);

很显然,您将要编写一堆测试用例,并确定这是否是您想要的