iBoughtWinrar February 2016

c# Cut String at Capital Letter

I wanted to make a small program, where i essentially have a lot of doubles for the atom mass for each atom. I want to be able to write a molecule formula into a textbox, whereafter the program should be able to calculate the molar mass, however, i dont know how i can cut the string from the textbox, so that for instance i can get from inserting "NaCl" into the textbox, the value of my Na double plus the value of my Cl double.

namespace WindowsFormsApplication33
{
    public partial class Form1 : Form
    {
        double H = 1.00794;
        double He = 4.002602;
        double Li = 6.941;
        double Be = 9.012182;
        ...

These are just all my doubles, now what i want a button to do:

        private void button1_Click(object sender, EventArgs e)
        {
            //take the different atoms in the molecule formula from a textbox,
            //get the value of all those doubles, and add them all together to get
            //a final value, for instance: NaCl = Na + Cl = 22.98976928 + 35.453 = 58.44276928
        }

Also, i want to be able to write H2SO4, which essentially is H*2 + S + O*4, how would i go about doing that?

Thank you in advance

Answers


Helic February 2016

void Main()
{
    string text = "NiNaCiKi";
    Regex reg = new Regex("[A-Z]{1}[a-z]*");
    var props = reg.Matches(text).Cast<Match>().Select(m=>m.Value).ToList();

    Chem ch = new Chem();

    var sum = typeof(Chem)
    .GetProperties()
    .Where(p=>props.Contains(p.Name))
    .Cast<PropertyInfo>()
    .Select(val=> (double)val.GetValue(ch)).Sum();

    Console.WriteLine(sum);
}

public class Chem
{
    public double Na {get {return 4;}}
    public double N {get {return 2;}}
    public double Ci {get {return 1;}}
}


Murray Hart February 2016

Dictionary<string, double> Chemicals = new Dictionary<string, double>() { { "H", 1.00794 }, { "He", 4.002602 }, { "Li", 6.941 }, { "Be", 9.012182 } };
        List<string> Properties = new List<string>();

        Regex reg = new Regex("[A-Z]{1}[a-z0-9]*");
        Properties = reg.Matches(txtInput.Text).Cast<Match>().Select(m => m.Value).ToList();

        double Total = 0;
        foreach (var Property in Properties)
        {
            var result = Regex.Match(Property, @"\d+$").Value;

            int resultAsInt;
            int.TryParse(result, out resultAsInt);

            if (resultAsInt > 0)
            {
                Total += Chemicals[Property.Substring(0, Property.Length - result.Length)] * resultAsInt;
            }
            else
            {
                Total += Chemicals[Property];
            }

        }

        lblOutput.Text = "Total: " + Total.ToString();

Post Status

Asked in February 2016
Viewed 3,789 times
Voted 9
Answered 2 times

Search




Leave an answer