簡體   English   中英

做清單中的任何項目 <string> 包含一個單獨的字符串的一部分

[英]Do any items in List<string> contain part of a separate string

假設我有如下所示的List<string>

  • 蘋果
  • 桃子
  • 李子

然后在一個字符串中,如果我有:

I would like to eat a pear today

(忽略大小寫。)在這種情況下,II會希望為true因為在列表和字符串中都找到了pear 但是,如果我有一個字符串:

I would like to eat a strawberry today

然后我會得到false因為在句子中沒有找到List<string>'s

我一直在玩各種事情,例如:

string result = Fruits.FirstOrDefault(s => s.IndexOf(sentence) > 0);

其中FruitsList<string>sentence是另一個字符串。 沒有釘。

嘗試這個:

bool result = Fruits.Any(s => sentence.ToLower().Contains(s.ToLower()));

要么

bool result = Fruits.Any(s => sentence.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0);

您需要以這種方式檢查=>

string result = Fruits.Any(s => sentence.IndexOf(s) > -1);

要么

string result = Fruits.Any(s => sentence.Contains(s));

如果您願意采用其他方法,則可以使用以下方法來完成:

public static bool ListItemInString(List<string> listOfStrings, string stringToCheck) {
    foreach(string str in listOfStrings) {
        if (stringToCheck.ToUpper().Contains(str.ToUpper())) {
            // return true if any of the list items are found in stringToCheck
            return true;
        }
    }
    // if the method has not returned true by this point then we return false
    // to indicate none of the list items were found within the string
    return false;
}

此方法遍歷您的列表,並根據您指定的字符串檢查每個項目。 如果在foreach循環中的任何時候發現字符串中包含列表項之一,它將返回try,否則它將返回false。 它還通過在搜索字符串之前將兩個字符串都轉換為大寫來考慮不區分大小寫的請求。

編輯 :我知道這更多是一種手動方法。 如果此操作被執行多次,則可以類似地將此帖子上的先前答案用作一種提高代碼可讀性的方法。

根據最初的問題,如果您正在尋找句子中匹配的字符串而不是布爾結果,則以下代碼應會有所幫助:

List<string> Fruits = new List<string> { "Apple", "Pear", "Peach", "Plum" };
var sentence = "I would like to eat a pear and apple today";
var sentenceLower = sentence.ToLower(); 
var delimiter = ",";
var match = Fruits
  .Where(s => sentenceLower.Contains(s.ToLower()))
  .Aggregate((i, j) => i + delimiter + j);

暫無
暫無

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

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