• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

convert "forty five" to "45"

 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm looking for an elegant way to convert one thru one hundred to "1" thru "100". The end result can either be an integer or a String representation of the value. Is there a clever way to accomplish this transformation or do I need to create a hashmap with 100 entries mapping the text to the number?
Many thanks!
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There may not be an elegant way to pull this off. You could use a combination of Maps and Regexes that employ capturing groups but anyway you slice it the logic gets nasty. For example English has numbers like eleven, twelve, fifteen, eighteen which would have to be handled with logic separate from teens like fourteen, sixteen, seventeen which could be handled in a similar manner to twenty one, twenty two, twenty three by dropping the white space (or dash) between the words. Then there would need to be logic that allowed one, two, three, etc to stand alone or to only follow twenty, thirty, forty, etc and reverse that for twenty, thirty, forty, etc. If you used two capturing groups for some of the teens, then you would need to check for those that do not comply as mentioned above. And one must be allowed to precede hundred.
 
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The best I could come up with was 27 nested "if" statements.


Tom Blough
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Take Tom's solution, and put the string literals and the integers into a HashMap (you'd have to wrap the ints as Integer objects.) Then the main loop is just a single HashMap lookup:
 
reply
    Bookmark Topic Watch Topic
  • New Topic