Replace all occurrences of a substring with another string in C#
This post will discuss how to replace all occurrences of a substring with another string in C#.
The Regex.Replace method replaces all matching occurrences of a substring with the specified replacement string. The pattern match is determined by a regular expression. It is available in the System.Text.RegularExpressions namespace and can be used either for removing all occurrences of a substring from a string or replacing all occurrences of a substring with another string.
1. Replace Substring
The following example demonstrates the usage of the Regex.Replace method by replacing all occurrences of a substring with another string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text.RegularExpressions; public static class StringExtensions { public static string Remove(this string input, string pattern, string replacement) { return Regex.Replace(input, pattern, replacement); } } public class Example { public static void Main() { String s = "a, b, c, d"; s = s.Replace(", ", ":"); Console.WriteLine(s); // a:b:c:d } } |
2. Remove Substring
To remove all occurrences of a substring from a string, you can provide the replacement string as an empty string in the Regex.Replace() method as follows.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text.RegularExpressions; public static class StringExtensions { public static string Remove(this string input, string pattern) { return Regex.Replace(input, pattern, string.Empty); } } public class Example { public static void Main() { String s = "a,b,c,d"; s = s.Remove(","); Console.WriteLine(s); // abcd } } |
Sometimes you need to remove consecutive duplicate occurrences of a delimiter from a string. It can be easily done using the + quantifier, which matches one or more occurrences of the pattern.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text.RegularExpressions; public static class StringExtensions { public static string Remove(this string input, string delim) { return Regex.Replace(input, delim + "+", delim); } } public class Example { public static void Main() { String s = "a,,b,c,d"; s = s.Remove(","); Console.WriteLine(s); // abcd } } |
That’s all about replacing all occurrences of a substring with another string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)