C# Split A String By Another String

2018-12-31 21:46发布

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 any way to split a string, with another string being the split by parameter? I've tried converting the splitter into a character array, with no luck.

In other words, I'd like to split the string:

THExxQUICKxxBROWNxxFOX

by xx, and return an array with values:

THE, QUICK, BROWN, FOX

9条回答
明月照影归
2楼-- · 2018-12-31 22:14
Regex.Split(string,"xx")

is the way I do it usually. Of course you'll need a

using System.Text.RegularExpressions;

but than again I need that lib all the time.

查看更多
浅入江南
3楼-- · 2018-12-31 22:19

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

"THExxQUICKxxBROWNxxFOX".Split(new [] {"xx"}, StringSplitOptions.None);
查看更多
初与友歌
4楼-- · 2018-12-31 22:19

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

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");
查看更多
登录 后发表回答