-6

I'm trying to replace words in a string using C#. Every time, I would like to get one matched word replaced.

Example:

"This is example 1, this is example 2, that is example 3."

Let's replace "is" with "###" one by one, then we should get 3 strings:

Desired outcome:

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

===== update =====

I'm new to Stack Overflow and thanks all for helping!

I was searching for match collection but didn't know how to replace word from a certain index (word matched index), so I ask this question. Thanks Dmitry for Linq solution and modifying the description of this question! Also thanks Anu for your solution!

hyper8ola
  • 1
  • 4

3 Answers3

0

You could use Regex and MatchCollection

public IEnumerable<string> GetStrings(string originalText,string wordToReplace)
{
    Regex rx = new Regex($" {wordToReplace} ",RegexOptions.Compiled | RegexOptions.IgnoreCase);
    MatchCollection matches = rx.Matches(originalText);

    foreach(Match match in matches)
    {
        var strBuilder = new StringBuilder(originalText);
        strBuilder.Remove(match.Index,match.Length);
        strBuilder.Insert(match.Index," ### ");
        yield return strBuilder.ToString();
    }
}

Sample Output

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 
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
0

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-1

Try something like this:

using System;

class MainClass {
  public static void Main (string[] args) {
      String str = "This is example 1, this is example 2, that is example 3.";
      while(str.Contains("is") ) {
        str.Replace("is", "###")
        Console.WriteLine (str);
      }
  }
}

This code runs until the string doesn't contain anymore "is" strings and each iteration it replaces one and outputs the current string.

Justin
  • 945
  • 12
  • 26
  • 1. `str.Replace("is", "###")` replaces all `is` in the first "iteration" 2. the return value of `str.Replace("is", "###")` needs to be assigned somewhere – fubo Nov 27 '19 at 06:40
  • True. We can use the functions described here: https://stackoverflow.com/questions/8809354/replace-first-occurrence-of-pattern-in-a-string or here: https://lonewolfonline.net/replace-first-occurrence-string/ to do that – Justin Nov 27 '19 at 06:42