How to add a space before and after conditional operator in a string?

Viewed 451

I have a string e.g "number1<=number2&&number3>number4||number2=number4" and having operator list as -

var operators = new List<string> {"=", "!", "<", ">", ">=", "<=", "!=","||","&&"};

So, expectation is to introduce a single space before and after each operator in the string.

"number1 <= number2 && number3 > number4 || number2 = number4"

I tried following code but its not working for instance, e.g, <, >=

public static string AddSpaceBeforeAndAfterOperator(string expression) {
  var operators = new List<string> {"=", "!", "<", ">", ">=", "<=", "!=", "||", "&&"};
  foreach (var op in operators) {
    var index = expression.IndexOf(op, StringComparison.Ordinal);
    if (index >= 0) {
      if (expression.Substring(index - 1) != " ") {
        expression = expression.Insert(index-1, " ");
      }
    expression = expression.Insert(index + op.Length + 1, " ");
    }
  }
  return expression;
}  

Note: The Operator list is coming as random.

Any help would be appreciated!

2 Answers

I would recommend a regex solution.

First, you need to escape all your operators, join them together with |:

var operatorsString = string.Join("|", 
    operators.OrderByDescending(x => x.Length).Select(Regex.Escape).ToArray()
);
// OrderByDescending here because we want the longer operators to be matched first.

Next, create the regex:

var regex = $"\\s*({operatorString})\\s*";

Using the operators array in the question, the array looks like this:

\s*(<=|>=|!=|==|\|\||&&|=|!|<|>)\s?*

Note that \s* is used to check if the operator is already surrounded by spaces. If it is, those spaces will be matched and replaced.

The replacement is:

 $1 

Code:

Regex.Replace(input, regex, " $1 ");

Note the leading and trailing space.

Also note that Regex is inside the System.Text.RegularExpressions namespace.

Demo

Im not sure if this is the most effective way to do this, but is is rally simple by using replace

public static string AddSpaceBeforeAndAfterOperator(string expression)
{
    var operators = new List<string> { "=", "!", "<", ">", ">=", "<=", "!=", "||", "&&" };
    foreach (var op in operators)
    {
        expression = expression.Replace(op, " " + op + " ");
    }

    return expression;
 }
Related