Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio: writeln;
- import std.array: split;
- import std.string: strip, indexOf;
- import re = std.regex;
- struct Atom {
- string name;
- short quantity;
- }
- //struct Molecule {
- // Atom[] atoms;
- //}
- struct Molecule {
- string[] atoms;
- }
- struct ChemicalEquation {
- Molecule[] reactants;
- Molecule[] products;
- }
- void main() {
- auto input = "Al + Fe2O4 -> Fe + Al2O3";
- try {
- auto tokens = stringToChemicalEquation(input);
- writeln(tokens);
- } catch (Exception e) {
- writeln(e.msg);
- }
- }
- ChemicalEquation stringToChemicalEquation(string str) {
- if (indexOf(str, "->") == -1)
- throw new Exception("Il manque un produit à la réaction !");
- auto chemicalEquation = ChemicalEquation();
- auto parts = split(str, "->");
- parts = trimArray(parts);
- auto reactants = split(parts[0], "+");
- reactants = trimArray(reactants);
- auto products = split(parts[1], "+");
- products = trimArray(products);
- Molecule[] reactantsMolecules = [];
- for (auto i = 0 ; i < reactants.length ; i++) {
- auto product = reactants[i];
- auto molecule = stringToMolecule(product);
- reactantsMolecules ~= molecule;
- }
- Molecule[] productsMolecules = [];
- for (auto i = 0 ; i < products.length ; i++) {
- auto product = products[i];
- auto molecule = stringToMolecule(product);
- productsMolecules ~= molecule;
- }
- chemicalEquation.reactants = reactantsMolecules;
- chemicalEquation.products = productsMolecules;
- return chemicalEquation;
- }
- Molecule stringToMolecule(string str) {
- auto atoms1 = re.matchAll(str, re.regex("[A-Z][a-z]*[0-9]*"));
- string[] atoms2 = [];
- foreach (atom ; atoms1)
- atoms2 ~= atom.hit;
- auto molecule = Molecule();
- molecule.atoms = atoms2;
- return molecule;
- }
- string[] trimArray(string[] arr) {
- for (auto i = 0 ; i < arr.length ; i++)
- arr[i] = strip(arr[i]);
- return arr;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement