EN
C# / .NET - replace all occurrences of string
0
points
In this article, we would like to show you how to replace all occurrences of the string in C# / .NET.
Quick solution:
string text = "ABC ABC ABC";
string replacement = "X";
string result = text.Replace("C", replacement);
Console.WriteLine(result); // ABX ABX ABX
1. Practical example using string Replace() method
In this example, we use Replace() method to replace all occurrences of the "C" in the text string with "X".
using System;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABC ABC ABC";
string replacement = "X";
string result = text.Replace("C", replacement);
Console.WriteLine("Original text: " + text); // ABC ABC ABC
Console.WriteLine("Modified text: " + result); // ABX ABX ABX
}
}
Output:
Original text: ABC ABC ABC
Modified text: ABX ABX ABX