简体   繁体   中英

Retrieving specific numbers from a string

I'm implementing complex numbers structure and I want users to have a possibility to insert values into Re and Im fields via property Geo , which is a geometric interpretation of a complex number eg (5,-3).

struct Cplx
{
    public double Re;
    public double Im;

    public string Geo
    {
        get
        {
            return "(" + Re + "," + Im + ")";
        }
    }
}

I don't know how to make the set accessor. Basically, I want to retrieve numbers x, y from (x,y) string so I can put them into double fields.

Just parse value which contains input like (5,-3), remove parenthesis and spaces and convert values to double.

set
{
    var input = value.Split(new[] { '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries);
    Re = Convert.ToDouble(input[0]);
    Im = Convert.ToDouble(input[1]);
}

Just a note, structs should be immutable, so I would advise to pass values to a constructor instead of setting them via a property. This would be a proper way to do it

struct Cplx
{
    public readonly double Re;
    public readonly double Im;

    public string Geo
    {
        get
        {
            return "(" + Re + "," + Im + ")";
        }
    }

    public Cplx(double re, double im)
    {
        Re = re;
        Im = im;
    }

    public Cplx(string cplx)
    {
        var input = cplx.Split(new[] { '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries);
        Re = Convert.ToDouble(input[0]);
        Im = Convert.ToDouble(input[1]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM