Home >Backend Development >C++ >How to Replace Only the First Instance of a String in .NET?
First instance of string replacement in .NET
.NET provides several ways to replace the first occurrence in a string. The most straightforward approach is to use a combination of the IndexOf
method to find the index of the first match, and then use the string's Substring
method to build the replaced string. Here is sample code to implement this functionality:
<code class="language-csharp">string ReplaceFirst(string text, string search, string replace) { int pos = text.IndexOf(search); if (pos >= 0) { return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } return text; }</code>
Example:
<code class="language-csharp">string str = "The brown brown fox jumps over the lazy dog"; str = ReplaceFirst(str, "brown", "quick"); // str 现在是 "The quick brown fox jumps over the lazy dog"</code>
Additional notes:
Regex.Replace(String, String, Int32)
method, but it may not be as efficient as the custom method provided here. The above is the detailed content of How to Replace Only the First Instance of a String in .NET?. For more information, please follow other related articles on the PHP Chinese website!