Search code examples
c#split

Can you split a string and keep the split char(s)?


Is there a way to split a string but keep the split char(s), if you do this:

"A+B+C+D+E+F+G+H".Split(new char[] { '+' });

you get

A
B
C
D
E
F
G
H

Is there a way to use split so it would keep the split char:

A
+B
+C
+D
+E
+F
+G
+H

or if you were to have + in front of A then

+A
+B
+C
+D
+E
+F
+G
+H

Solution

  • You can use Regex.Split with a pattern that doesn't consume delimiter characters:

    var pattern = @"(?=\+)";
    
    var ans = Regex.Split(src, pattern);
    

    This will create an empty entry if there is a leading + as there is an implied split before the +.

    You could use LINQ to remove the empty entries if they aren't wanted:

    var ans2 = Regex.Split(src, pattern).Where(s => !String.IsNullOrEmpty(s)).ToArray();
    

    Alternatively, you could use Regex.Matches to extract the full matching patterns:

    var ans3 = Regex.Matches(src, @"(?:^|\+)[^+]*").Cast<Match>().Select(m => m.Value).ToArray();