繁体   English   中英

比较列表成字符串

[英]compare list into string

我需要检查列表中的字符串是否在text to searchtext to search中找到以及列表中有多少个字符串

这是我要搜索的字符串

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting 
industry. Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer took a galley 
of type and scrambled it to make a type specimen book. 

这是我的清单

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the
printing and typesetting 
industry. Lorem Ipsum has been the
industry's standard dummy
text ever since the 1500s, when
an unknown printer took a galley 

我创建了一个示例代码

string longString = "word1, word2, word 3";

List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" });

for (int i = 0; i < myList.Count; i++)
{
    if (myList.Any(str => longString.Contains(str)))
    {
        Console.WriteLine("success!");
    }
    else
    {
        Console.WriteLine("fail!");
    }
}

但是它success打印了三遍。 它应该只有一次。 我该如何工作? 如何跳过已用于搜索项目的项目。

因为您正在myList中循环,它会成功打印三遍 尝试这样:

string longString = "word1, word2, word 3";

List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" });

if (myList.Any(str => longString.Contains(str)))
{
    Console.WriteLine("success!");
}
else
{
     Console.WriteLine("fail!");
}

更换

if (myList.Any(str => longString.Contains(str)))

if (longString.Contains(myList[i]))

检查您的字符串中是否存在逐项检查。

您当前的版本会检查3x是否存在其中的任何一项,在大小写word 3总是正确的

要获得计数,可以使用以下方法:

string longString = "word1, word2, word 3";
List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" });
int count = myList.Count(s => s.Any(a => longString.Contains(s)));

周期更改为:

   foreach (string check in myList)
            {
                if (longString.Any(str => longString.Contains(check)))
                {
                    Console.WriteLine("success!");
                }
                else
                {
                    Console.WriteLine("fail!");
                }
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM