Words To Numbers
This algorithm converts English words to decimal numbers.
/*****Please include following header files*****/
// string
// vector
/***********************************************/
/*****Please use following namespaces*****/
// std
/*****************************************/
static inline string RTrim(const string& s, const string& delimiters = " \f\n\r\t\v") {
return s.substr(0, s.find_last_not_of(delimiters) + 1);
}
static inline string LTrim(const string& s, const string& delimiters = " \f\n\r\t\v") {
return s.substr(s.find_first_not_of(delimiters));
}
static inline string Trim(const string& s, const string& delimiters = " \f\n\r\t\v") {
return LTrim(RTrim(s, delimiters), delimiters);
}
static uint64_t WordsToNumbers(string words) {
if (words.empty()) return 0;
words = Trim(words);
words += ' ';
uint64_t number = 0;
vector<string> singles = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
vector<string> teens = { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
vector<string> tens = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninty" };
vector<string> powers = { "", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion" };
int singlesLength = singles.size();
int teensLength = teens.size();
int tensLength = tens.size();
int powersLength = powers.size();
for (int i = powersLength - 1; i >= 0; i--)
{
if (!(powers[i].empty()))
{
int index = words.find(powers[i], 0);
if (index >= 0 && words[index + powers[i].length()] == ' ')
{
uint64_t count = WordsToNumbers(words.substr(0, index));
number += count * (uint64_t)pow(1000, i);
words = words.erase(0, index);
}
}
}
{
int index = words.find("hundred", 0);
if (index >= 0 && words[index + string("hundred").length()] == ' ')
{
uint64_t count = WordsToNumbers(words.substr(0, index));
number += count * 100;
words = words.erase(0, index);
}
}
for (int i = tensLength - 1; i >= 0; i--)
{
if (!(tens[i].empty()))
{
int index = words.find(tens[i], 0);
if (index >= 0 && words[index + tens[i].length()] == ' ')
{
number += (unsigned int)(i * 10);
words = words.erase(0, index);
}
}
}
for (int i = teensLength - 1; i >= 0; i--)
{
if (!(teens[i].empty()))
{
int index = words.find(teens[i], 0);
if (index >= 0 && words[index + teens[i].length()] == ' ')
{
number += (unsigned int)(i + 10);
words = words.erase(0, index);
}
}
}
for (int i = singlesLength - 1; i >= 0; i--)
{
if (!(singles[i].empty()))
{
int index = words.find(singles[i] + ' ', 0);
if (index >= 0 && words[index + singles[i].length()] == ' ')
{
number += (unsigned int)(i);
words = words.erase(0, index);
}
}
}
return number;
}
Example
string data = "five quadrillion four hundred seventy eight trillion seven hundred seventy five billion five hundred forty four million eight hundred seventy nine thousand five hundred ninty nine";
uint64_t value = WordsToNumbers(data);
Output
5478775544879599