Replace only first occurance of substring from string in C#

By Santhosh N

This explains how to replace only first occurance of a substring from string in C#.

In C#, to replace a substring from string we can use Replace function of string but it replaces all occurances of the substring.
To replace only desired number of occurances or only fist occurence, we could use Regex for this.

string str = "This is a sample string to explain sub string operation.";
           Regex regReplace = new Regex("string");
            string res = regReplace.Replace(str, "str", 1);

This results "This is a sample str to explain sub string operation."

Related FAQs

This is how trimming of a string can be done in javascript is simpler manner.
This is how you can check if the given string is in numeric format or not in c#
Replace only first occurance of substring from string in C#  (1807 Views)