Whenever you want to replace a string inside another string, .NET Framework offers the Replace() function. It is a function that accepts two string parameters, the string to be replaced and the string to replace with. Its usage is very simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; namespace HelloWorld { class Program { private static void Main(string[] args) { string greeting = "Hello World!"; Console.WriteLine(greeting); string replaced = greeting.Replace("World", "Yulia"); Console.WriteLine(replaced); Console.Read(); } } } |
The above code produces the following output:
The explanation is just as simple: we provided the string that we wanted to be replaced, and the string with which we wanted it to be replaced, then we output the result.
A helper feature for the Replace() function is the use of a regular expressions. Regular expressions allow us to find some rather complicated text patterns, such as phone numbers, postal codes, email addresses, etc. We will learn about them later.
Tags: regex, regular expressions, replace, string operations, substring