c#在大写字母中剪切字符串

时间:2016-02-08 11:08:01

标签: c# string

我想做一个小程序,其中我基本上有很多双原子质量的双原子。我希望能够将分子公式写入文本框,然后程序应该能够计算摩尔质量,但是,我不知道我如何从文本框中剪切字符串,以便例如我可以从插入中获取“NaCl”进入文本框,我的Na的值加上我的Cl的值加倍。

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

这些只是我所有的双打,现在我想要一个按钮:

        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
        }

另外,我希望能够写出H2SO4,基本上是H * 2 + S + O * 4,我该怎么做呢?

提前谢谢

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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