0

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

P.S. 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;
 }
3
  • Regex is the way to go for you: msdn.microsoft.com/es-es/library/… Commented May 27, 2013 at 14:41
  • Make conditions for this. Like if (string.Contains("+") || string.Containts("plus") || string.Contains("and") {...} Commented May 27, 2013 at 14:43
  • 9
    The question is quite vague. What exactly are your requirements? Can there be just about anything between the numbers? Can there be more than 2 numbers? Any targeted solution will need more information than what you have given us so far. Commented May 27, 2013 at 14:44

9 Answers 9

9
string input="5+5";

var numbers = Regex.Matches(input, @"\d+")
                   .Cast<Match>()
                   .Select(m => m.Value)
                   .ToList();
Sign up to request clarification or add additional context in comments.

Comments

2

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 e.g. this one over at Code Project (and the updated version over at CodePlex).

Using the parser/tool above, you could do things like:

enter image description here

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.

Comments

0

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

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

0

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.

Comments

0

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 "+":
            .
            .

            .


        }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.