【问题标题】:Is there any possible way to check which Split() element is used?有没有办法检查使用了哪个 Split() 元素?
【发布时间】:2020-11-19 17:25:54
【问题描述】:

我有这个代码:

string expresie = Console.ReadLine();          
char[] separatori = {'+', '-'};
string[] elementeExpresie = expresie.Split(separatori);

int elem0 = int.Parse(elementeExpresie[0]);
int elem1 = int.Parse(elementeExpresie[1]);
int elem2 = int.Parse(elementeExpresie[2]);
/////////////////////////////////////////////////////////////////////////////////////////
int operatie1 = 0;

if (separatori[0] == '+')
{
    operatie1 = elem0+elem1;
}
else if (separatori[0] == '-')
{
    operatie1 = elem0-elem1;
}           
           
int operatie2 = 0;

if(separatori[1] == '+')
{
    operatie2 = operatie1+elem2;
}
else if(separatori[1] == '-')
{
    operatie2 = operatie1-elem2;
}

Console.WriteLine(operatie2);

我必须编写一个类似于计算器的程序,用户在控制台中插入一个算术表达式,最后,它必须显示计算结果。代码的第二部分不起作用,因为我需要检查使用了哪个 char[] 元素; “+”或“-”。这实际上是我的问题:有什么方法可以检查使用了哪个 Split() 元素?

例子: string mathExpression = "10 + 11 - 5"

控制台输出:16

PS:这是学校作业,我需要使用.split方法。

【问题讨论】:

  • 不,无法判断string.Split 使用了哪个分隔符。如果用户总是输入1 + 2 而从不输入1+2,你可以用空格代替吗?
  • Split 从返回的字符串中删除用于拆分的分隔符。您无法使用 split 来发现拆分过程中使用了哪个分隔符。
  • 你应该在空格上分割(只是不要将任何参数传递给Split),然后检查每个部分以确定它是数字还是运算符。
  • 不要简单地使用Split,而是使用一组正则表达式来tokenize您的输入。例如,标记最终会变成 ("10", numeric), ("+", operator), ("11", numeric), ("-", operator), ("5", numeric)。然后,一旦你得到一组标记,解析它们到你想要的表达式
  • 考虑拆分运算符,一次一个。考虑10+11-5-2+6+7-4。在+ 上拆分会得到1011-5-267-4。然后遍历结果以查看字符串中是否有剩余的运算符。如果有,则对其进行拆分(使11-5-2 变为1152)。这是解析该行的一种非常复杂的方法

标签: c# string split calculator


【解决方案1】:

用填充运算符替换您的运算符,并在填充字符上拆分。

例如

var pad = "\0";
var input = "1+2";
var operators = new string[] { "+", "-" };
foreach (var operator in operators)
{
    input = input.Replace(operator, pad + operator + pad);
}
var tokens = input.Split( new string[] { pad } , StringSplitOptions.RemoveEmptyEntries);

Console.WriteLine(tokens[0]); // Outputs "1"
Console.WriteLine(tokens[1]); // Outputs "+"
Console.WriteLine(tokens[2]); // Outputs "2"

【讨论】:

    【解决方案2】:

    一个想法是在空格上拆分,这样您就有了一组操作数和运算符。然后您可以执行以下操作:

    string expression = Console.ReadLine();
    string[] expParts = expression.Split();
    
    int operand1 = int.Parse(expParts[0]);
    string operator1 = expParts[1];
    int operand2 = int.Parse(expParts[2]);
    string operator2 = expParts[3];
    int operand3 = int.Parse(expParts[4]);
    
    int result = operand1;
    
    if (operator1 == "+")
    {
        result += operand2;
    }
    else if (operator1 == "-")
    {
        result -= operand2;
    }
    
    if (operator2 == "+")
    {
        result += operand3;
    }
    else if (operator2 == "-")
    {
        result -= operand3;
    }
    
    Console.WriteLine(result);
    

    这里的缺点是它需要精确的字符串格式 ("10 + 11 - 5")。如果有人输入"10+11-5",就不行了。

    【讨论】:

      猜你喜欢
      • 2019-09-08
      • 2015-07-03
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2018-10-02
      相关资源
      最近更新 更多