-1

So i want to ask that suppose if i am taking input like 2+5 in one line so i want to separate them in 3 different variables like int a=2, b=3 and char operator = '+'

P.S: just trying to tweak my simple calculator program

Cœur
  • 37,241
  • 25
  • 195
  • 267
Danial Ahmed
  • 856
  • 1
  • 10
  • 26

4 Answers4

2

Try using the split method

Splits a string into substrings that are based on the characters in an array.

SYNTAX:

public string[] Split(params char[] separator)

See more here

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

You can use a regular expression to get each component more reliably (i.e., this supports int numbers of any length):

class Program
{
    static void Main(string[] args)
    {
        var input = "20+5";

        var regex = new Regex(@"(\d+)(.)(\d+)");

        if (regex.IsMatch(input))
        {
            var match = regex.Match(input);
            var a = match.Groups[1].Value;
            var op = match.Groups[2].Value;
            var b = match.Groups[3].Value;

            Console.WriteLine($"a: {a}");
            Console.WriteLine($"operator: {op}");
            Console.WriteLine($"b: {b}");
        }
    }
}

Outputs

a: 20
operator: +
b: 5
m1kael
  • 2,801
  • 1
  • 15
  • 14
0

Try this:

 string strResult = Console.ReadLine();

 //On here, we are splitting your result if user type one line both numbers with "+" symbol. After splitting, 
// we are converting them to integer then storing the result to array of integer.
 int[] intArray = strResult.Split('+').Select(x => int.Parse(x)).ToArray();

Now you can now access your numbers via its index

 intArray[0] 
 //or 
 intArray[1]
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
0

So i want to ask that suppose if i am taking input like 2+5 in one line so i want to separate them in 3 different variables like int a=2, b=3 and char operator = '+'

you can use params array to pass any number of parameters to a method and then you can just split them.

Example:

public int Result(params char[] input){
  // split the input 
  // any necessary parsing/converting etc.
  // do some calculation
 // return the value
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • This does not even address the OP's original problem, which is how to parse the input. This explicitly takes three different inputs. – Steve Feb 25 '17 at 14:43
  • if you read our chat within his question, he clearly stated that he was happy if i provided an alternative solution....... – Ousmane D. Feb 25 '17 at 14:44
  • Then the question should have been edited as well. The page should stand on its own. – Steve Feb 25 '17 at 21:50