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
Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!
In order to split by a string you'll have to use the string array overload.
The easiest way is to use
String.Replace
:Or more simply:
This is also easy:
I generally like to use my own extension for that:
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.
There is an overload of Split that takes strings.
You can use either of these StringSplitOptions
So if the string is "THExxQUICKxxxxBROWNxxFOX",
StringSplitOptions.None
will return an empty entry in the array for the "xxxx" part whileStringSplitOptions.RemoveEmptyEntries
will not.