簡體   English   中英

檢查單詞是否包含字符串列表中的子字符串

[英]check if word contains substring from list of strings

我已經看到了使用linq這樣做的示例,如下所示:

List<string> list = new List<string> {"One", "Two", "Three", "Four", "five", "six" };
string text = "OneTwoThreeFour";

list.Any(s => text.contains(s))

但這是否適用於所有可能的單詞? 意思是,如果我有一個由3個較小的單詞組成的大單詞(沒有用任何特殊字符分隔),它將捕獲所有3個子單詞嗎? 還是一旦找到匹配項就停止檢查?

我要完成的工作是采用"OneTwoThreeFour"類的詞,並在每個唯一詞之間添加空格或破折號,使其為"One Two Three Four"

有一個更好的方法嗎?

並且有可能獲得作為匹配返回的“字符串”?

更新以涵蓋任何一種情況:

您可以通過在大寫字母前添加空格並按空格分割來從text獲取單詞列表。 然后,您可以使用SequenceEqual()將結果與list進行比較。

這是一個例子:

static void Main(string[] args)
{
    List<string> list = new List<string> {"One", "Two", "Three", "Four", "Five" };
    string text = "OneTwoThreeFourFive";

    string withSpaces = AddSpacesToSentence(text, true);
    List<string> list2 = withSpaces.Split(' ').ToList();

    bool b = list.SequenceEqual(list2);
}

// Refer to: https://stackoverflow.com/a/272929/4551527
static string AddSpacesToSentence(string text, bool preserveAcronyms)
{
    if (string.IsNullOrWhiteSpace(text))
        return string.Empty;
    StringBuilder newText = new StringBuilder(text.Length * 2);
    newText.Append(text[0]);
    for (int i = 1; i < text.Length; i++)
    {
        if (char.IsUpper(text[i]))
            if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
                (preserveAcronyms && char.IsUpper(text[i - 1]) &&
                    i < text.Length - 1 && !char.IsUpper(text[i + 1])))
                newText.Append(' ');
        newText.Append(text[i]);
    }
    return newText.ToString();
}

請注意,我從以下答案中獲得了AddSpacesToSentence的實現: https ://stackoverflow.com/a/272929/4551527

另一個更新

順便說一句,如果詞語列表中的順序並不重要(換句話說:“ONETWO”應匹配{“二”,“一”}),然后就可以Sort()做前兩個列表SequenceEquals()


原創(當我認為這是單向比較時)

您可以使用All()代替:

List<string> list = new List<string> {"One", "Two", "Three", "Four" };
string text = "OneTwoThreeFour";

list.All(s => text.Contains(s))

如果序列中的所有元素都滿足謂詞(此處為contains),則返回true。

上面的代碼段返回true。 如果在list添加“五”(但text保持不變),則它將返回false。

一種簡單的方法可能是遍歷項目列表並進行String Replace (我使用過StringBuilder ,也可以使用String.Replace ),例如:

List<string> list = new List<string> { "One", "Two", "Three", "Four", "five", "six" };
string text = "OneTwoThreeFour";
StringBuilder sb = new StringBuilder(text);
foreach (var str in list)
{
    sb.Replace(str, " " + str + " ");
}

string modifiedText = sb.ToString();

這將為您提供modifiedText = " One Two Three Four " 另外,您不必檢查列表中是否存在Any項目。 如果列表中不存在該項目,則String.Replace將不執行任何操作。

對於:

它會捕獲所有3個子詞嗎? 還是一旦找到匹配項就停止檢查?

一旦找到匹配項,它將停止。 您正在使用Enumerable.Any ,一旦找到匹配項,將不執行進一步的比較。

暫無
暫無

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

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