olidev olidev - 9 days ago 5
C# Question

C#: split a string with delimiters but keep the delimiters in the result

I would like to split a string with delimiters but keep the delimiters in the result

How would I do this in c#?

Thanks in advance!

Answer

If you want the delimiter to be its "own split", you can use Regex.Split e.g.:

string input = "plum-pear";
string pattern = "(-)";

string[] substrings = Regex.Split(input, pattern);    // Split on hyphens
foreach (string match in substrings)
{
   Console.WriteLine("'{0}'", match);
}
// The method writes the following to the console:
//    'plum'
//    '-'
//    'pear'