c# 以大写字母剪切字符串

本文关键字:字符串 大写字母 | 更新日期: 2023-09-27 18:33:36

我想做一个小程序,其中我基本上有很多双精度的原子质量。我希望能够将分子公式写入文本框,此后程序应该能够计算摩尔质量,但是,我不知道如何从文本框中剪切字符串,以便例如我可以通过将"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,我将如何做到这一点?

提前谢谢你

c# 以大写字母剪切字符串

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