[Solved] Replace words in a string one by one using C#


You can query the source string with a help of Linq while matching whole word of interest with a help of regular expressions:

using System.Linq;
using System.Text.RegularExpressions;

...

string source =
  @"This is example 1, this is example 2, that is example 3";

string word = "is";

string[] result = Regex
  .Matches(source, $@"\b{Regex.Escape(word)}\b", RegexOptions.IgnoreCase)
  .Cast<Match>()
  .Select(match => 
     $"{source.Substring(0, match.Index)}###{source.Substring(match.Index + match.Length)}")
  .ToArray();

Let’s have a look at result array:

Console.Write(string.Join(Environment.NewLine, result));

Outcome:

This ### example 1, this is example 2, that is example 3
This is example 1, this ### example 2, that is example 3
This is example 1, this is example 2, that ### example 3

0

solved Replace words in a string one by one using C#