C#
The following code will do what you asked for (and nothing more).
string input = "3+10-5";
string pattern = @"([-+^*\/])";
string[] substrings = Regex.Split(input, pattern);
// results in substrings = {"3", "+", "10", "-", "5"}
By using Regex.Split
instead of String.Split
you are able to retrieve the math operators as well. This is done by putting the math operators in a capture group ( )
. If you're not familiar with regular expressions you should google the basics.
The code above will stubbornly use the math operators to split your string. If the string doesn't make sense, the method doesn't care and may even produce unexpected results. For example "5//10-"
will result in {"5", "/", "", "10", "-", ""}
. Note that only one /
is returned and empty strings are added.
You can use more complex regular expressions to check if your string is a valid mathematical expression before you try to split it. For example ^(\d+(?:.\d+)?+([-+*^\/]\g<1>)?)$
would check if your string consists of a decimal number and zero or more combinations of an operator and another decimal number.