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
The easiest way is to use String.Replace
:
string myString = "THExxQUICKxxBROWNxxFOX";
mystring = mystring.Replace("xx", ", ");
Or more simply:
string myString = "THExxQUICKxxBROWNxxFOX".Replace("xx", ", ");
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.
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.
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");