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

前端 未结 9 1643
天涯浪人
天涯浪人 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:10

    A little off-topic maybe, but while case insensitive replacement is covered by the standard replace function since (?), here a little function that adds text before and/or after a substring without changing the case of the substring:

        Public Shared Function StrWrap(Haystack As String, Needle As String, Optional AddBefore As String = "", Optional AddAfter As String = "") As String
            Dim Index = Haystack.ToLower.IndexOf(Needle.ToLower)
            If Index < 0 Then Return Haystack
            Return Haystack.Substring(0, Index) + AddBefore + Haystack.Substring(Index, Needle.Length) + AddAfter + Haystack.Substring(Index + Needle.Length)
        End Function
    

    Usage: StrWrap("Hello World Test", "hello", "Hi, ", " and Ahoi")

    Result: "Hi, Hello and Ahoi World Test"


    Standard case insensitive replacement:

    Replace("Hello World Test", "hello", "Hi", , Compare:=CompareMethod.Text)

提交回复
热议问题