Function to calculate product of numbers using 'x' operator?

90 views Asked by At

What function will input a string which could either contain numbers or the multiplication of two numbers using the 'x' character as an operator?

For example:

  • If the input is "6 x 11" then the output should be 66.
  • If the input is "78" then the output should be 78.
2

There are 2 answers

2
Inisheer On

Well, you could use several System.String methods to accomplish this. What have you tried?

One option:

public int GetValue(string input)
{
    int output = 0;

    if (input.Contains("x"))
    {
        string[] a = input.Split('x');
        int x = int.Parse(a[0]);
        int y = int.Parse(a[1]);

        output = x * y;
    }
    else
    {
        output = int.Parse(input);
    }
    return output;
}

Of course, this ignores any input validation.

0
Sumeshk On

Check this

        public int GetProduct(string input)
        {
            int result = 1;
            input = input.ToUpper();

            if (input.Contains("X"))
            {
                string[] array = input.Split('x');
                for (int index = 0; index < array.Length; index++)
                {
                    if (IsNumber(array[index]))
                    {
                        result = result * Convert.ToInt32(array[index]);
                    }
                }
            }
            else
            {
                result = Convert.ToInt32(input);
            }
            return result;
        }

        bool IsNumber(string text)
        {
            Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
            return regex.IsMatch(text);
        }