简体   繁体   中英

Parse multiple values from string c#

Suppose I have written "5 and 6" or "5+6". How can I assign 5 and 6 to two different variables in c# ?

PS I also want to do certain work if certain chars are found in string. Suppose I have written 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 ).

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

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 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 .

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. 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. If you want to make "calculator" you will need something more, like Binary Trees or Stack.

Use the String.Split method. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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