简体   繁体   English

从字符串 c# 中解析多个值

[英]Parse multiple values from string c#

Suppose I have written "5 and 6" or "5+6".假设我已经写了“5 和 6”或“5+6”。 How can I assign 5 and 6 to two different variables in c# ?如何在 c# 中将 5 和 6 分配给两个不同的变量?

PS I also want to do certain work if certain chars are found in string. PS如果在字符串中找到某些字符,我也想做某些工作。 Suppose I have written 5+5.假设我已经写了 5+5。 Will this code do that ?这段代码会这样做吗?

 if(string.Contains("+"))
 {
     sum=x+y;
 }
string input="5+5";

var numbers = Regex.Matches(input, @"\d+")
                   .Cast<Match>()
                   .Select(m => m.Value)
                   .ToList();

Personally, I would vote against doing some splitting and regular expression stuff.就个人而言,我会投票反对做一些拆分和正则表达式的事情。

Instead I would (and did in the past) use one of the many Expression Evaluation libraries, like eg this one over at Code Project (and the updated version over at CodePlex ).相反,我会(过去也这样做过)使用许多表达式评估库之一,例如Code Project 上的这个库(以及CodePlex 上更新版本)。

Using the parser/tool above, you could do things like:使用上面的解析器/工具,您可以执行以下操作:

在此处输入图片说明

A simple expression evaluation then could look like:一个简单的表达式评估可能如下所示:

Expression e = new Expression("5 + 6");
Debug.Assert(11 == e.Evaluate());

To me this is much more error-proof than doing the parsing all by myself, including regular expressions and the like.对我来说,这比我自己进行解析(包括正则表达式等)更能防错。

You should use another name for your string than string您应该为字符串使用另一个名称而不是string

var numbers = yourString.Split("+");
var sum = Convert.ToInt32(numbers[0]) + Convert.ToInt32(numbers[1]);

Note: Thats an implementation without any error checking or error handling...注意:这是一个没有任何错误检查或错误处理的实现......

You can use String.Split method like;您可以使用String.Split方法,例如;

string s = "5 and 6";
string[] a = s.Split(new string[] { "and", "+" }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(a[0].Trim());
Console.WriteLine(a[1].Trim());

Here is a DEMO .这是一个DEMO

If you want to assign numbers from string to variables, you will have to parse string and make conversion.如果要将字符串中的数字分配给变量,则必须解析字符串并进行转换。

Simple example, if you have text with only one number简单示例,如果您的文本只有一个数字

string text = "500";
int num = int.Parse(text);

Now, if you want to parse something more complicated, you can use split() and/or regex to get all numbers and operators between them.现在,如果你想解析更复杂的东西,你可以使用 split() 和/或 regex 来获取它们之间的所有数字和运算符。 Than you just iterate array and assign numbers to variables.比您只是迭代数组并将数字分配给变量。

string text = "500+400";
if (text.Contains("+"))
{
 String[] data = text.Split("+");
 int a = int.Parse(data[0]);
 int b = int.Parse(data[1]);
 int res = a + b;
}

Basicly, if you have just 2 numbers and operazor between them, its ok.基本上,如果您只有 2 个数字和它们之间的操作符,那就可以了。 If you want to make "calculator" you will need something more, like Binary Trees or Stack.如果你想制作“计算器”,你需要更多的东西,比如二叉树或堆栈。

Use the String.Split method.使用 String.Split 方法。 It splits your string rom the given character and returns a string array containing the value that is broken down into multiple pieces depending on the character to break, in this case, its "+".它将您的字符串从给定的字符中拆分出来,并返回一个字符串数组,该数组包含根据要中断的字符(在本例中为“+”)分解为多个部分的值。

        int x = 0;
        int y = 0;
        int z = 0;

        string value = "5+6";
        if (value.Contains("+"))
        {
            string[] returnedArray = value.Split('+');
            x = Convert.ToInt32(returnedArray[0]);
            y = Convert.ToInt32(returnedArray[1]);
            z = x + y;
        }

Something like this may helpful像这样的事情可能会有所帮助

string strMy = "5&6";
char[] arr = strMy.ToCharArray();
List<int> list = new List<int>();
foreach (char item in arr)
{
  int value;
  if (int.TryParse(item.ToString(), out value))
  {
    list.Add(item);
  }
}

list will contains all the integer values列表将包含所有整数值

Use regex to get those value and then switch on the operand to do the calculation使用正则表达式获取这些值,然后打开操作数进行计算

        string str = "51 + 6";
        str = str.Replace(" ", "");
        Regex regex = new Regex(@"(?<rightHand>\d+)(?<operand>\+|and)(?<leftHand>\d+)");

        var match = regex.Match(str);
        int rightHand = int.Parse(match.Groups["rightHand"].Value);
        int leftHand = int.Parse(match.Groups["leftHand"].Value);
        string op = match.Groups["operand"].Value;

        switch (op)
        {
            case "+":
            .
            .

            .


        }

Split function maybe is comfortable in use but it is space inefficient because it needs array of strings拆分函数可能使用起来很舒服,但空间效率低下,因为它需要字符串数组
Maybe Trim(), IndexOf(), Substring() can replace Split() function也许 Trim()、IndexOf()、Substring() 可以代替 Split() 函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM