How to replace the first occurrence of a substring in a string with C#

1 Answer

0 votes
using System;

class Program
{
    static void Main()
    {
        string s = "aa bb cc dd ee cc";
        string result = ReplaceFirst(s, "cc", "YY");
        
        Console.WriteLine(result); 
    }

    static string ReplaceFirst(string input, string search, string replace)
    {
        int index = input.IndexOf(search);
        
        if (index < 0) return input;
        
        return input.Substring(0, index) + replace + input.Substring(index + search.Length);
    }
}



/*
run:

aa bb YY dd ee cc

*/

 



answered Jul 20, 2025 by avibootz
...