簡體   English   中英

快速搜索巨大字符串中的多個部分字符串

[英]Swiftly search for multiple partial strings in a huge string

我需要檢查字符串的所有部分是否都像

A=1&AW=43&KO=96&R=7&WW=15&ZJ=80

像這樣的大字符串:

A=1&AG=77&AW=43&.....&KF=11&KO=96&.....&QW=55&R=7&....&WV=1&WW=15&....ZJ=80&

我的代碼在上拆分了第一個字符串,並使用Contains 但是持續時間太長,因為大字符串最多可包含800000個字符。

有沒有更好/更快的方法呢?

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlInt32 EquipmentCompare(SqlString equip, SqlString comp)         
    {
        SqlInt32 result = 1;

        if (comp.IsNull)
        {
            result = 1;
        }
        else
        {
            string equipment = "&" + equip.ToString();
            string compString = comp.ToString() + "! ";

            while (compString.Length > 1)
            {
                string sub = compString.Substring(0, compString.IndexOf("!"));
                compString = compString.Substring(compString.IndexOf("!")+1);
                string[] elements = sub.Split('&');
                foreach (string i in elements)
                {
                    if (i.StartsWith("~"))
                    {
                        if (equipment.Contains("&" + i.Substring(1) + "&"))
                        {
                            result = 0;
                            break;
                        }
                    }
                    else if (!equipment.Contains("&" + i + "&"))
                    {
                        result = 0;
                        break;
                    }
                    else
                    {
                        result = 1;
                        continue;
                    }
                }           
                if (result == 1)
                {
                    break;
                }
            }
        }
        return result;         
    }
}

我認為您可以通過使用HashSet來加快代碼的速度。 嘗試這個:

var str1 = "A=1&AW=43&KO=96&R=7&WW=15&ZJ=80";
var str2 = "A=1&AG=77&AW=43&.....&KF=11&KO=96&.....&QW=55&R=7&....&WV=1&WW=15&....ZJ=80&";

var largeStringSet = new HashSet<string>(str2.Split('&'));
var allPartsIncluded = str1.Split('&').All(s => largeStringSet.Contains(s));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM