December 08, 2019, 08:48:46 AM
Forum Rules: Read This Before Posting


Topic: Parsing a chemical formula  (Read 3218 times)

0 Members and 1 Guest are viewing this topic.

Offline ajri02

  • New Member
  • **
  • Posts: 7
  • Mole Snacks: +1/-3
Parsing a chemical formula
« on: June 08, 2016, 10:21:34 AM »
I'm trying to create a java app that takes a chemical formula like "CH3COOH" and returns some sort of collection full of their symbols.

CH3COOH would return [C,H,H,H,C,O,O,H]

I already have something that is kinda working, but it's very complicated and uses a lot of code with a lot of nested if-else structures and loops.

Is there a way I can do this by using some kind of regular expression with String.split or maybe in some other brilliant simple code?

Online AWK

  • Retired Staff
  • Sr. Member
  • *
  • Posts: 6911
  • Mole Snacks: +491/-81
  • Gender: Male
Re: Parsing a chemical formula
« Reply #1 on: June 08, 2016, 10:56:33 AM »
AWK

Online Borek

  • Mr. pH
  • Administrator
  • Deity Member
  • *
  • Posts: 25358
  • Mole Snacks: +1663/-398
  • Gender: Male
  • I am known to be occasionally wrong.
    • Chembuddy
Re: Parsing a chemical formula
« Reply #2 on: June 08, 2016, 11:58:01 AM »
Is there a way I can do this by using some kind of regular expression

Long ago I did something similar in php, with a callback function generating replacement strings from the string and the number of repetitions. It worked by replacing each item with a subscript by a list, so that for example (NH4)2SO4 would gradually become
NH4NH4SO4 (removing parentheses first)
NHHHHNH4SO4 (proceeding with indices from the left)
NHHHHNHHHHSO4
NHHHHNHHHHSOOOO

ChemBuddy chemical calculators - stoichiometry, pH, concentration, buffer preparation, titrations.info, pH-meter.info

Offline ajri02

  • New Member
  • **
  • Posts: 7
  • Mole Snacks: +1/-3
Re: Parsing a chemical formula
« Reply #3 on: June 08, 2016, 08:13:57 PM »
Thank Borek

Sponsored Links