Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# split input of a string

Tags:

c#

split

I've recently moved from c++ to c# in my classes and I have looked all over and haven't found much. I am having the following problem. I am supposed to be able to let the user add a complex number. For Example

-3.2 - 4.1i I want to split and store as (-3.2) - (4.1i)

I know I can split at the - sign, but there are some problems like

4 + 3.2i or even just a single number 3.2i.

Any help or insight would be appreciated.

like image 780
Derked Avatar asked Nov 28 '25 14:11

Derked


1 Answers

By matching all the valid input with a regex it's a matter of assembling it after. The regex works by

  • [0-9]+ matching 0-n numbers
  • [.]? matching 0 or 1 dot
  • [0-9]+ matching 0-n numbers
  • i? matching 0 or 1 "i"
  • | or
  • [+-*/]? matching 0 or 1 of the operators +, -, * or /

.

public static void ParseComplex(string input)
{
    char[] operators = new[] { '+', '-', '*', '/' };

    Regex regex = new Regex("[0-9]+[.]?[0-9]+i?|[+-/*]?");
    foreach (Match match in regex.Matches(input))
    {
        if (string.IsNullOrEmpty(match.Value))
            continue;

        if (operators.Contains(match.Value[0]))
        {
            Console.WriteLine("operator {0}", match.Value[0]);
            continue;
        }

        if (match.Value.EndsWith("i"))
        {
            Console.WriteLine("imaginary part {0}", match.Value);
            continue;

        }
        else
        {
            Console.WriteLine("real part {0}", match.Value);

        }
    }
}
like image 176
default Avatar answered Nov 30 '25 03:11

default



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!