How do I return which delimiter split a certain string? (C#)

Viewed 54

I'm splitting a user input string at the math operators, I want to know if there's some way to remember exactly which operator acted as the delimiter within the code?

private void button1_Click(object sender, EventArgs e)
{
    string userInput = textBox1.Text;
    char[] operators = { '+', '-', '*', '/' };
    //splits the entered string into substrings after encountering operator characters
    string[] operands = userInput.Split(operators);
}
1 Answers

I suggest tokenizing instead of splitting (in the simplest case you can use Regex.Split instead of string.Split):

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string userInput = textBox1.Text;
  char[] operators = { '+', '-', '*', '/' };
  
  string pattern = "(" + string.Join("|", operators
    .Select(c => Regex.Escape(c.ToString()))) + ")";

  string[] tokens = Regex.Split(userInput, pattern);

If textBox1.Text == "5 * 6 + 7", tokens will be {"5 ", "*", "6", "+", "7"}. All you have to do now is to check for each token if it's operation or operand. Something like this:

  // {"5", "6", "7"}
  string[] operands = tokens
    .Where(token => !operators.Any(op => op.ToString() == token))
    .Select(item => item.Trim())
    .Where(item => !string.IsNullOrEmpty(item))
    .ToArray();

  // {"*", "+"}
  string[] operations = tokens
    .Where(token => operators.Any(op => op.ToString() == token))
    .ToArray(); 
Related