I would like to split a string with delimiters but keep the delimiters in the result.
How would I do this 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With