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
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
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)
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
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]
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
}