簡體   English   中英

如何檢查字符串是否包含字符串數組中的字符串?

[英]How do I check if a string contains a string from an array of strings?

所以這是我的例子

string test = "Hello World, I am testing this string.";
string[] myWords = {"testing", "string"};

如何檢查字符串測試是否包含以下任何單詞? 如果確實包含我該怎么做,以便可以用等於該長度的星號替換那些單詞?

您可以使用正則表達式:

public string AstrixSomeWords(string test)
{
    Regex regex = new Regex(@"\b\w+\b");

    return regex.Replace(test, AsterixWord);
}

private string AsterixWord(Match match)
{
    string word = match.Groups[0].Value;
    if (myWords.Contains(word))
        return new String('*', word.Length);   
    else
        return word;
}

我已經檢查了代碼,它似乎按預期工作。

如果myWords中的單詞數量很大,您可以考慮使用HashSet以獲得更好的性能。

var containsAny = myWords.Any(x => test.Contains(x));
bool cont = false;
string test = "Hello World, I am testing this string.";
string[] myWords = { "testing", "string" };
foreach (string a in myWords)
{
    if( test.Contains(a))
    {
        int no = a.Length;
        test = test.Replace(a, new string('*', no));
    }
}

像這樣

foreach (var word in mywords){

    if(test.Contains(word )){

        string astr = new string("*", word.Length);

        test.Replace(word, astr);
    }
}

編輯:精制

暫無
暫無

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

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