Split a string by another string in C#

后端 未结 10 1479
小蘑菇
小蘑菇 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:07

    The easiest way is to use String.Replace:

    string myString = "THExxQUICKxxBROWNxxFOX";
    mystring = mystring.Replace("xx", ", ");
    

    Or more simply:

    string myString = "THExxQUICKxxBROWNxxFOX".Replace("xx", ", ");
    
    0 讨论(0)
  • 2020-11-22 11:08
    Regex.Split(string, "xx")
    

    is the way I do it usually.


    Of course you'll need:

    using System.Text.RegularExpressions;
    

    or :

    System.Text.RegularExpressions.Regex.Split(string, "xx")
    

    but then again I need that library all the time.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 11:08

    The previous answers are all correct. I go one step further and make C# work for me by defining an extension method on String:

    public static class Extensions
    {
        public static string[] Split(this string toSplit, string splitOn) {
            return toSplit.Split(new string[] { splitOn }, StringSplitOptions.None);
        }
    }
    

    That way I can call it on any string in the simple way I naively expected the first time I tried to accomplish this:

    "a big long string with stuff to split on".Split("g str");
    
    0 讨论(0)
提交回复
热议问题