首页 > 解决方案 > 字符串列表包含所有子组件

问题描述

字符串列表 G 是:

[0] : {"1,2,5"}
[1] : {"1,2,4,5,6"}
[2] : {"2,4,6"}
[3] : {"1,4,6"}

通过以下命令,我们得出结论"1,4"存在于列表 G[3] 中:

if (G[i].Contains("1,4")) { //code here }

如何修改上述命令,除了功能(包含),"1,4"存在于列表 G[1] 中?

程序代码

    for (int i = 0; i < candid.Count; i++) 
    {
        foreach (TransactionTP b in transactions)
        {
            string search = candid[i];
            var searchNumbers = search.Split(',').Select(int.Parse).ToList();
            for (int j = 0; j < G.Count; j++)
            {
                IEnumerable<int> numbers = G[j].Split(',').Select(int.Parse);
                int idx = 0;
                foreach (var number in numbers)
                {
                    if (number == searchNumbers[idx])
                    {
                        idx++;
                    }
                    if (idx == searchNumbers.Count)
                    {
                        arraye[i] = arraye[i] + (b.transactionUtility);
                        break;
                    }
                }
            }
        }
    }

更新:

搜索词的顺序很重要。

标签: c#

解决方案


为了保持你匹配的集合的顺序(在这种情况下是 4,1),你需要评估每个字符串,跟踪你在匹配中的位置。

string[] G = new[]
{
    "1,2,5",
    "1,2,4,5,6",
    "2,4,6",
    "1,4,6"
};

string search = "1,4";
var searchNumbers = search.Split(',').Select(int.Parse).ToList();

for (int i = 0; i < G.Length; i++)
{
    // Convert the string into an enumeration of numbers
    IEnumerable<int> numbers = G[i].Split(',').Select(int.Parse);

    // Index to keep track of the search
    int idx = 0;

    // Loop through the input set sequentially
    foreach (var number in numbers)
    {
        // Check if the input matches the next expected number
        if (number == searchNumbers[idx])
        {
            idx++;
        }

        if (idx == searchNumbers.Count)
        {
            Console.WriteLine("String {0} matched", G[i]);
            break;
        }
    }
}

推荐阅读