How do I replace the *first instance* of a string in .NET?

后端 未结 14 1129
忘掉有多难
忘掉有多难 2020-11-22 16:41

I want to replace the first occurrence in a given string.

How can I accomplish this in .NET?

14条回答
  •  猫巷女王i
    2020-11-22 16:58

    And because there is also VB.NET to consider, I would like to offer up:

    Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String
        Dim pos As Integer = text.IndexOf(search)
        If pos >= 0 Then
            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
        End If
        Return text 
    End Function
    

提交回复
热议问题