3

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.

9
  • 3
    Sounds like what you need is a regular expression.. Commented Jan 17, 2014 at 17:48
  • To @Default's comment on "base paring on presence of i: likely 4 is perfectly valid complex number for that assignment (need teacher's input here :) ) Commented Jan 17, 2014 at 17:49
  • if there's always spaces between the numbers and operations you could try to parse it with the Complex type. (No space would mean one number) Commented Jan 17, 2014 at 17:51
  • You may want to look at regexlib.com/… and get some ideas whether regular expressions will help. Commented Jan 17, 2014 at 17:53
  • 1
    For @Default's suggestion on Complex - turns out System.Numerics.Complex does not have Parse of any kind - so useful to store, no use for parsing. Commented Jan 17, 2014 at 18:07

2 Answers 2

1

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);

        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

This still has pleanty of flaws and ways it can blow up, but in kinda works.

struct Complex
{
    float re, im;

    public static Complex Parse(string text)
    {
        text=text.Replace(" ", string.Empty); //trim spaces
        float re=0, im=0;
        int i_index=text.IndexOf('i');
        if(i_index>=0) //if no 'i' is present process as real only
        {
            text=text.Substring(0, i_index); //ignore all after i

            int i=0;
            //find start of digits
            while(i<text.Length&&(text[i]=='+'||text[i]=='-'))
            {
                i++;
            }
            //find end of digits
            while(i<text.Length&&(char.IsNumber(text, i)|| text.Substring(i).StartsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)))
            {
                i++;
            }
            // parse real (first) portion
            float.TryParse(text.Substring(0, i), out re);
            // had 'i' but no numbers
            if(text.Length==0)
            {
                im=1;
            }
            else
            {
                //parse remaining value as imaginary
                text=text.Substring(i+1);
                float.TryParse(text, out im);
            }
        }
        else
        {
            float.TryParse(text, out re);
        }
        // Build complex number
        return new Complex() { re=re, im=im };
    }
    public override string ToString()
    {
        return string.Format("({0},{1})", re, im);
    }
}
class Program
{
    static void Main(string[] args)
    {
        var test=new[] { "1", "i", "5+2i", "-5+2i", "+5-2i", "0.23+0.72i" };

        for(int i=0; i<test.Length; i++)
        {
            Debug.Print( Complex.Parse(test[i]).ToString() );
        }
    }
}

resut:

(1,0)
(0,1)
(5,2)
(-5,2)
(5,2)
(0.23,0.72)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.