Split a string by another string in C#

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

    As of .NET Core 2.0, there is an override that takes a string.

    So now you can do "THExxQUICKxxBROWNxxFOX".Split("xx").

    See https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-2.0#System_String_Split_System_String_System_StringSplitOptions_

    0 讨论(0)
  • 2020-11-22 10:46

    There's an overload of String.Split for this:

    "THExxQUICKxxBROWNxxFOX".Split(new [] {"xx"}, StringSplitOptions.None);
    
    0 讨论(0)
  • 2020-11-22 10:49

    There is an overload of Split that takes strings.

    "THExxQUICKxxBROWNxxFOX".Split(new [] { "xx" }, StringSplitOptions.None);
    

    You can use either of these StringSplitOptions

    • None - The return value includes array elements that contain an empty string
    • RemoveEmptyEntries - The return value does not include array elements that contain an empty string

    So if the string is "THExxQUICKxxxxBROWNxxFOX", StringSplitOptions.None will return an empty entry in the array for the "xxxx" part while StringSplitOptions.RemoveEmptyEntries will not.

    0 讨论(0)
  • 2020-11-22 10:50

    This is also easy:

    string data = "THExxQUICKxxBROWNxxFOX";
    string[] arr = data.Split("xx".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    
    0 讨论(0)
  • 2020-11-22 10:52

    In order to split by a string you'll have to use the string array overload.

    string data = "THExxQUICKxxBROWNxxFOX";
    
    return data.Split(new string[] { "xx" }, StringSplitOptions.None);
    
    0 讨论(0)
  • 2020-11-22 10:59
    string data = "THExxQUICKxxBROWNxxFOX";
    
    return data.Replace("xx","|").Split('|');
    

    Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!

    0 讨论(0)
提交回复
热议问题