简体   繁体   English

如何检查字符串是否包含字符串数组中的字符串?

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

So here is my example 所以这是我的例子

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

How do I check if the string test contains any of the following words? 如何检查字符串测试是否包含以下任何单词? If it does contain how do I make it so that it can replace those words with a number of asterisks equal to the length of that? 如果确实包含我该怎么做,以便可以用等于该长度的星号替换那些单词?

You can use a regex: 您可以使用正则表达式:

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;
}

I have checked the code and it seems to work as expected. 我已经检查了代码,它似乎按预期工作。

If the number of words in myWords is large you might consider using HashSet for better performance. 如果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));
    }
}

Something like this 像这样

foreach (var word in mywords){

    if(test.Contains(word )){

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

        test.Replace(word, astr);
    }
}

EDIT: Refined 编辑:精制

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

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