Here are two quick extension methods that will allow you to replace just the first or last occurrence in a string with another. I’ve provided them as extension methods but they could just as easily just be implemented as a function. Note, that if you use them as an extension method with the Extension() call above the method you will want to import System.Runtime.CompilerServices
at the top of that code file.
VB.Net
''' <summary>
''' An extension method that replaces the first occurance of a specified string.
''' </summary>
''' <param name="str"></param>
''' <param name="searchTxt"></param>
''' <param name="replaceTxt"></param>
<Extension()> _
Public Function ReplaceFirst(ByVal str As String, searchTxt As String, replaceTxt As String) As String
Dim pos As Integer = str.IndexOf(searchTxt)
If pos < 0 Then
Return str
End If
Return str.Substring(0, pos) + replaceTxt + str.Substring(pos + searchTxt.Length)
End Function
''' <summary>
''' An extension method that replaces the last occurance of a specified string.
''' </summary>
''' <param name="str"></param>
''' <param name="searchTxt"></param>
''' <param name="replaceTxt"></param>
<Extension()> _
Public Function ReplaceLast(ByVal str As String, searchTxt As String, replaceTxt As String) As String
Dim pos As Integer = str.LastIndexOf(searchTxt)
If pos < 0 Then
Return str
End If
Return str.Substring(0, pos) + replaceTxt + str.Substring(pos + searchTxt.Length)
End Function
C#
/// <summary>
/// An extension method that replaces the first occurance of a specified string.
/// </summary>
/// <param name="str"></param>
/// <param name="searchTxt"></param>
/// <param name="replaceTxt"></param>
public static string ReplaceFirst(this string str, string searchTxt, string replaceTxt)
{
int pos = str.IndexOf(searchTxt);
if (pos < 0)
{
return str;
}
return str.Substring(0, pos) + replaceTxt + str.Substring(pos + searchTxt.Length);
}
/// <summary>
/// An extension method that replaces the last occurance of a specified string.
/// </summary>
/// <param name="str"></param>
/// <param name="searchTxt"></param>
/// <param name="replaceTxt"></param>
public static string ReplaceLast(this string str, string searchTxt, string replaceTxt)
{
int pos = str.LastIndexOf(searchTxt);
if (pos < 0)
{
return str;
}
return str.Substring(0, pos) + replaceTxt + str.Substring(pos + searchTxt.Length);
}