1

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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for checking word boundaries - the other solutions would also match "test", which is probably not intended.
2
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));
    }
}

1 Comment

So how do I make it so that it would change those words into astericks equal to the length of the word that was supposed to be filtered?
2
var containsAny = myWords.Any(x => test.Contains(x));

Comments

1

Something like this

foreach (var word in mywords){

    if(test.Contains(word )){

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

        test.Replace(word, astr);
    }
}

EDIT: Refined

2 Comments

You should use new string('*', word.Length) instead.
Never knew that existed. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.