Replace first occurrence of pattern in a string

Views: 1214
Comments: 0
Like/Unlike: 1
Posted On: 14-Jun-2017 02:14 

Share:   fb twitter linkedin
Brian
2376 Points
13 Posts

Introduction
We don't have inbuilt method to replace first occurrence in a string. In this article we will use string method IndexOf and Substring to accomplish this. Also we will see how to use Regex.Replace to accomplish the same.

I) Using string methods IndexOf and Substring

public static class StringExtensionMethods
{
    public static string ReplaceFirstOccurrence(this string text, string search, string replace)
    {
        int pos = text.IndexOf(search);
        if (pos < 0)
        {
            return text;
        }
        return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

Example 1

 

string str = "The brown fox jumps over the lazy brown dog";
str = ReplaceFirstOccurrence(str, "brown", "quick");

//Output: "The quick fox jumps over the lazy brown dog"

Here is an Extension Method that could also work

public static class StringExtensionMethods
{
    public static string ReplaceFirstOccurrence(this string text, string search, string replace)
    {
        int pos = text.IndexOf(search);
        if (pos < 0)
        {
            return text;
        }
        return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

Example 2

string str = "The brown fox jumps over the lazy brown dog"; 
str = str.ReplaceFirstOccurrence("brown", "quick");

//Output: "The quick fox jumps over the lazy brown dog"


II) Using Regex.Replace

 

using System.Text.RegularExpressions; 

Regex regex = new Regex("brown");
string result = regex.Replace("The brown fox jumps over the lazy brown dog", "quick", 1);

//Output: "The quick fox jumps over the lazy brown dog"

Conclusion
Now, we have two approach to replace first occurrence in a string normat approach and Regex.Replace approach. Hope, it will be helpful.

0 Comments
 Log In to Chat