c# - Calculate molecular weight based on chemical formula -


i trying write program calculate molecular weight of given molecule based on chemical formula.

this code can split molecular formula "ch3oh" array {c h 3 o h} here, way use split text calculate molecular weight?

string input = moleculetextbox.text; string pattern = @"([0-9]?\d*|[a-z][a-z]{0,2}?\d*)"; string[] sunstrings = regex.split(input,pattern); 

first of all, you'd need parse string , turn "h3" "hhh", etc. might this:

var x = "ch3oh".replace(/([a-z])([2-9])/gi, function(_,c,n) { return new array(1+parseint(n)).join(c); }); 

first group being matched character, , second group being number of repetitions.

you have string looks "chhhoh". can split line array 1 character @ each index, .split(''), , map each value molecular mass. need define sort of lookup table. i'm using reduce take care of mapping , addition in 1 go:

var mass = { c: 12.011, h: 1.008, o: 15.999 }; var weight = x.split('').reduce(function(sum,element) { return sum + mass[element]; }, 0); 

Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -