Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string with delimiters but keep the delimiters in the result in C#

Tags:

string

c#

split

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

How would I do this in C#?

like image 799
olidev Avatar asked Jan 13 '11 12:01

olidev


People also ask

How split a string using multiple delimiters in C#?

To split a String with multiple delimiter strings in C#, call Split() on the string instance and pass the delimiter strings array as argument to this method. The method returns a String array with the splits. Reference to C# String. Split() method.

Can you split a string in C?

Splitting a string using strtok() in C In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

How do you split a string without delimiters?

Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.


2 Answers

If the split chars were ,, ., and ;, I'd try:

using System.Text.RegularExpressions; ...     string[] parts = Regex.Split(originalString, @"(?<=[.,;])") 

(?<=PATTERN) is positive look-behind for PATTERN. It should match at any place where the preceding text fits PATTERN so there should be a match (and a split) after each occurrence of any of the characters.

like image 106
codybartfast Avatar answered Sep 23 '22 12:09

codybartfast


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' 

So if you are looking for splitting a mathematical formula, you can use the following Regex

@"([*()\^\/]|(?<!E)[\+\-])"  

This will ensure you can also use constants like 1E-02 and avoid having them split into 1E, - and 02

So:

Regex.Split("10E-02*x+sin(x)^2", @"([*()\^\/]|(?<!E)[\+\-])") 

Yields:

  • 10E-02
  • *
  • x
  • +
  • sin
  • (
  • x
  • )
  • ^
  • 2
like image 41
veggerby Avatar answered Sep 25 '22 12:09

veggerby