Пошук та заміна тексту

C#:
Пошук та заміна тексту

How to (Як це зробити)

C# provides String.Replace method to replace text. Here’s a simple example:

using System;

public class TextReplaceExample
{
    static void Main()
    {
        string originalText = "Привіт, як справи?";
        string newText = originalText.Replace("справи", "життя");

        Console.WriteLine(newText);
    }
}

Output:

Привіт, як життя?

For more complex patterns, you can use Regex.Replace from the System.Text.RegularExpressions namespace:

using System;
using System.Text.RegularExpressions;

class RegexReplaceExample
{
    static void Main()
    {
        string input = "Купи 10 апельсинів і 12 бананів.";
        string pattern = @"\d+";
        string replacement = "#";

        string result = Regex.Replace(input, pattern, replacement);
        Console.WriteLine(result);
    }
}

Output:

Купи # апельсинів і # бананів.

Deep Dive (Поглиблений Огляд)

Searching and replacing text has been around since the early days of computing. Editors like sed in Unix made it popular in the ’70s. In .NET, String.Replace is straightforward for simple text changes, but Regex is powerful for patterns.

Alternatives include text-processing tools or integrated development environment (IDE) features like Visual Studio’s “Find and Replace”.

Implementation-wise, beware of memory overhead with large strings when using String.Replace. StringBuilder can be more efficient. Regex has a performance cost but is optimized for complex patterns.

See Also (Дивіться Також)