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.
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 numbersi? 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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With