Searching and replacing text

C#:
Searching and replacing text

How to:

C# makes text manipulation pretty straightforward. Below, check out the string.Replace method to swap out words.

using System;

public class Program
{
    public static void Main()
    {
        string phrase = "Hello, World!";
        string updatedPhrase = phrase.Replace("World", "C#");
        
        Console.WriteLine(updatedPhrase); // Output: Hello, C#!
    }
}

No rocket science, right? But say we want to ignore case or replace only whole words? Regex to the rescue:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string phrase = "Apples grow on trees. apple pies are tasty.";
        string pattern = "\\bapple\\b"; // \b is a word boundary in Regex
        string replacement = "Orange";
        
        string updatedPhrase = Regex.Replace(phrase, pattern, replacement, RegexOptions.IgnoreCase);

        Console.WriteLine(updatedPhrase); // Output: Oranges grow on trees. Orange pies are tasty.
    }
}

Deep Dive

Back in the day, manipulating strings was a hassle. C was all we had, and it meant dealing with character arrays and manual iterations. C# gave us a gift: easy string handling.

If string.Replace or Regex.Replace don’t cut it, we’ve got options. For huge texts or complex patterns, consider writing a custom parser or use libraries like Antlr.

Regex is powerful for pattern matching but can be slow. If performance is critical and you’re into the nitty-gritty details, measure and compare with StringBuilder for massive, iterative replacements.

See Also