簡體   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