Split a string by another string in C#

后端 未结 10 1610
小蘑菇
小蘑菇 2020-11-22 10:17

I\'ve been using the Split() method to split strings, but this only appears to work if you are splitting a string by a character. Is there a way to split a

10条回答
  •  滥情空心
    2020-11-22 11:08

    I generally like to use my own extension for that:

    string data = "THExxQUICKxxBROWNxxFOX";
    var dataspt = data.Split("xx");
    //>THE  QUICK  BROWN  FOX 
    
    
    //the extension class must be declared as static
    public static class StringExtension
    {   
        public static string[] Split(this string str, string splitter)
        {
            return str.Split(new[] { splitter }, StringSplitOptions.None);
        }
    }
    

    This will however lead to an Exception, if Microsoft decides to include this method-overload in later versions. It is also the likely reason why Microsoft has not included this method in the meantime: At least one company I worked for, used such an extension in all their C# projects.

    It may also be possible to conditionally define the method at runtime if it doesn't exist.

提交回复
热议问题