2

我需要比较几个字符串。

我有一个可以替换任何数字的通配符“%”(数字可以是任何大小)。

string str1 = "STRUCT[1].VARSTRUCT[10].VAR[1]";
string str2 = "STRUCT[%].VARSTRUCT[%].VAR[%]";
string str3 = "STRUCT[%].VARSTRUCT[%].VAR[2]";

CompareStrings(str1, str2); // Should return TRUE;
CompareStrings(str2, str3); // Should return TRUE;
CompareStrings(str1, str3); // SHould return FALSE;
4

2 回答 2

3

以下是对包含数字和表示数字的通配符的任意两个字符串执行此操作的方法:

    private static bool CompareStrings(string str1, string str2)
    {
        var ar1 = Regex.Matches(str1, @"[\d%]+").Cast<Match>().Select(m => m.Value).ToArray();
        var ar2 = Regex.Matches(str2, @"[\d%]+").Cast<Match>().Select(m => m.Value).ToArray();

        if (ar1.Length != ar2.Length)
            return false;

        // Check wildcards and numbers
        for (int i = 0; i < ar1.Length; i++)
            if (ar1[i] != ar2[i] && ar1[i] != "%" && ar2[i] != "%")
                return false;

        // Remove wildcards and numbers to check the other characters
        if (Regex.Replace(str1, @"[\d%]+", String.Empty) != Regex.Replace(str2, @"[\d%]+", String.Empty))
            return false;

       return true;
    }
于 2013-02-13T14:36:19.900 回答
2

一个非常快速且粗略的示例,说明如何执行此类操作..但它有效

class Program
{
    static void Main(string[] args)
    {

        string str1 = "STRUCT[1].VARSTRUCT[10].VAR[1]";
        string str2 = "STRUCT[%].VARSTRUCT[%].VAR[%]";
        string str3 = "STRUCT[%].VARSTRUCT[%].VAR[2]";

        Console.WriteLine("str1 - str2: " + SpecialComparers.AreEqual(str1, str2));
        Console.WriteLine("str2 - str3: " + SpecialComparers.AreEqual(str2, str3));
        Console.WriteLine("str1 - str3: " + SpecialComparers.AreEqual(str1, str3));

    }
}

class SpecialComparers
{
    public static bool AreEqual(String in1, String in2)
    {
        Regex re = new Regex(@"STRUCT\[(\d+|%)\]\.VARSTRUCT\[(\d+|%)\]\.VAR\[(\d+|%)\]");

        var values1 = re.Match(in1).Groups;
        var values2 = re.Match(in2).Groups;

        if (values1.Count != values2.Count) return false;

        for (int i = 1; i <= values1.Count; i++ )
        {
            if (!values1[i].ToString().Equals(values2[i].ToString())
                && !values1[i].ToString().Equals("%")
                && !values2[i].ToString().Equals("%")
            )
                return false;
        }
        return true;
    }
}
于 2013-02-13T14:21:01.673 回答