Suppose we have a string that represents an equation:
string ecuacion = "x^4-x^3-5x^2-x-6";
And we want to get the space between the operators:
char[] operadores = new char[] { '-', '+', '*', '/' };
If we use string.Split();
to separate the modules from each other in a list in the following way:
List<string> subEcuaciones = new List<string>();
subEcuaciones = ecuacion.Split(operadores, StringSplitOptions.None).ToList();
The result we get is:
x^4
x^3
5x^2
x
6
However I would like to preserve the operator by which they are delimited, i.e. get as a result:
x^4
-x^3
-5x^2
-x
-6
Is there a setting to preserve the operators?
It is best to use a regular expression as it
split
does not maintain the delimiter.In the following example I show you how it would be done using
Regex.Split
Result
It is not preserved. And that's the expected behavior of
string.Split()
, according to the documentation :That is, you use Split to split a string, you don't need delimiters. In fact, in your case, what you call a delimiter is not such, the symbols you mention have a semantic meaning for each of the subexpressions of your string, they do not have a delimiter meaning .
Take a look at this question where someone is faced with the same exercise you expose.