1
\$\begingroup\$

Given a list of strings paragraphs and words. Check each paragraphs's item for containing words's item as a substring. In the case of positive, replace all characters of this substring on 'x'.

I do it in the following way:

// In production, words.Length ~500
var words = new List<string>
{
    "technology",
    "word",
    "IBM",
    // ...
};

// In production, paragraphs.Length ~10,000 and paragraphs[i].Length ~200
var paragraphs = new List<string>
{
    "Microsoft Corporation is an American multinational technology corporation which produces computer software...",
    "Microsoft (the word being a portmanteau of \"microcomputer software\") was founded by Bill Gates and",
    "As of 2015, Microsoft is market-dominant in the IBM PC compatible operating system market and the office software",
    // ...
};

for (int i = 0; i < paragraphs.Count; i++)
{
    foreach (string word in words)
    {
        var template = new string('x', word.Length);
        paragraphs[i] = paragraphs[i].Replace(word, template);
    }
}

foreach (string para in paragraphs)
{
    Console.WriteLine(para);
}

enter image description here


I think that using algorithms is very bad since there is much String.Replace() calling. As you know, the string type is immutable and each String.Replace() allocates a new space in memory.

Please, review my implementation and help to improve.

\$\endgroup\$
2
  • \$\begingroup\$ Please edit your question so that the title describes the purpose of the code, rather than its mechanism. We really need to understand the motivational context to give good reviews. Thanks! \$\endgroup\$ Oct 28, 2021 at 20:11
  • \$\begingroup\$ This is generally called redaction just FYI. \$\endgroup\$
    – RobH
    Oct 29, 2021 at 7:18

1 Answer 1

5
\$\begingroup\$

Use StringBuilder.

When adding strings into StringBuilder it allows you to work with their characters without adding extra allocations, and whenever you're done, you can call ToString() to get the immutable string representation of it.

StringBuilder is often used when there is some repetitive executions on string/s or when the string that is going to be manipulated has a large size.

So, your work can be changed to this :

var builder = new StringBuilder();

for (int i = 0; i < paragraphs.Count; i++)
{
    builder.Append(paragraphs[i]);
    
    for(int x = 0; x < words.Count; x++)
    {
        builder.Replace(words[x], new string('x', word[x].Length)); 
    }

    paragraphs[i] = builder.ToString();
    
    builder.Clear();
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.