Is there a case insensitive string replace in .Net without using Regex?

前端 未结 9 1639
天涯浪人
天涯浪人 2020-12-11 00:45

I recently had to perform some string replacements in .net and found myself developing a regular expression replacement function for this purpose. After getting it to work I

9条回答
  •  佛祖请我去吃肉
    2020-12-11 01:20

    This is a VB.NET adaptation of rboarman's answer above with the necessary checks for null and empty strings to avoid an infinite loop.

    Public Function Replace(ByVal originalString As String, 
                            ByVal oldValue As String, 
                            ByVal newValue As String, 
                            ByVal comparisonType As StringComparison) As String
        If Not String.IsNullOrEmpty(originalString) AndAlso 
           Not String.IsNullOrEmpty(oldValue) AndAlso 
           newValue IsNot Nothing Then
            Dim startIndex As Int32
    
            Do While True
                startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType)
                If startIndex = -1 Then Exit Do
                originalString = originalString.Substring(0, startIndex) & newValue & 
                                 originalString.Substring(startIndex + oldValue.Length)
                startIndex += newValue.Length
            Loop
        End If
    
        Return originalString
    End Function
    

提交回复
热议问题