c# - 如何在字符串中的条件运算符前后添加空格?

标签 c# string c#-4.0

我有一个字符串,例如“number1<=number2&&number3>number4||number2=number4”,并且运算符列表为 -

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

因此,期望在字符串中每个运算符之前和之后引入一个空格。

数字1 <= 数字2 && 数字3 > 数字4 || 数字2 = 数字4

我尝试了以下代码,但它不起作用,例如 <, >=

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;
}  

注意:运算符(operator)列表是随机的。

如有任何帮助,我们将不胜感激!

最佳答案

我会推荐一个正则表达式解决方案。

首先,您需要转义所有运算符,将它们与 | 连接在一起:

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.

接下来,创建正则表达式:

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

使用问题中的operators数组,该数组如下所示:

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

请注意,\s* 用于检查运算符是否已被空格包围。如果是,这些空格将被匹配并替换。

替代品是:

 $1 

代码:

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

注意前导空格和尾随空格。

另请注意,Regex 位于 System.Text.RegularExpressions 命名空间内。

Demo

关于c# - 如何在字符串中的条件运算符前后添加空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53313758/

相关文章:

c# - 在html中使用c#执行if语句

c# - 使用 Entity Framework 时在哪里指定业务规则

visual-studio - complus异常代码-532462766

c# - iTextSharp Image.GetInstance 的 EMF 格式内存流

c# - Visual C# - 在哪里存储处理文件和工作而不是 C :\ProgramFiles?

Python 字符串函数 isidentifier()

我们可以在 C 中反转这个字符串吗?

java - 字符串与 == 比较的奇怪效果

c# - Xamarin PCLCrypto SHA256 给出不同的哈希值

c# - 对象属性不正确时的 Wcf (400) Bad Request