puretppc
puretppc

Reputation: 3292

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?

Upvotes: 1

Views: 76

Answers (4)

Shane van Wyk
Shane van Wyk

Reputation: 1900

Something like this

foreach (var word in mywords){

    if(test.Contains(word )){

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

        test.Replace(word, astr);
    }
}

EDIT: Refined

Upvotes: 1

user2509901
user2509901

Reputation:

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

Upvotes: 2

Casperah
Casperah

Reputation: 4564

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.

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

var containsAny = myWords.Any(x => test.Contains(x));

Upvotes: 2

Related Questions