文字列からC#の化学式(たとえば、Al2O3orO3またはCorの形式)を解析しようとしています。C11H22O12特定の元素の原子が1つしかない場合(たとえば、の酸素原子H2O)を除いて、正常に機能します。その問題をどのように修正できますか?さらに、化学式の文字列を解析するためのより良い方法はありますか?
ChemicalElementは、化学元素を表すクラスです。これには、AtomicNumber(int)、Name(string)、Symbol(string)のプロパティがあります。ChemicalFormulaComponentは、化学元素と原子数(式の一部など)を表すクラスです。これには、Element(ChemicalElement)、AtomCount(int)のプロパティがあります。
残りは理解できるほど明確でなければなりませんが(私は願っています)、答える前に、何か明確にできることがあればコメントで知らせてください。
これが私の現在のコードです:
/// <summary>
/// Parses a chemical formula from a string.
/// </summary>
/// <param name="chemicalFormula">The string to parse.</param>
/// <exception cref="FormatException">The chemical formula was in an invalid format.</exception>
public static Collection<ChemicalFormulaComponent> FormulaFromString(string chemicalFormula)
{
Collection<ChemicalFormulaComponent> formula = new Collection<ChemicalFormulaComponent>();
string nameBuffer = string.Empty;
int countBuffer = 0;
for (int i = 0; i < chemicalFormula.Length; i++)
{
char c = chemicalFormula[i];
if (!char.IsLetterOrDigit(c) || !char.IsUpper(chemicalFormula, 0))
{
throw new FormatException("Input string was in an incorrect format.");
}
else if (char.IsUpper(c))
{
// Add the chemical element and its atom count
if (countBuffer > 0)
{
formula.Add(new ChemicalFormulaComponent(ChemicalElement.ElementFromSymbol(nameBuffer), countBuffer));
// Reset
nameBuffer = string.Empty;
countBuffer = 0;
}
nameBuffer += c;
}
else if (char.IsLower(c))
{
nameBuffer += c;
}
else if (char.IsDigit(c))
{
if (countBuffer == 0)
{
countBuffer = c - '0';
}
else
{
countBuffer = (countBuffer * 10) + (c - '0');
}
}
}
return formula;
}