字符串-英语数字转换器(数据结构基础 第4周)

问题描述
字符串-英语数字转换器(数据结构基础 第4周)_第1张图片
分析
刚开始一直困惑怎么做,搜了别人的答案才了然:我们可以以thousand和million为分割。具体参见coursera数据结构字符串课后作业 的分析。

源码

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;

void printmap(map<string, int>& m) {
    m["negative"] = -1;
    m["zero"] = 0;m["one"] = 1;m["two"] = 2; m["three"] = 3; m["four"] = 4;m["five"] = 5; 
    m["six"] = 6; m["seven"] = 7; m["eight"] = 8; m["nine"] = 9; m["ten"] = 10;
    m["eleven"] = 11; m["twelve"] = 12; m["thirteen"] = 13;m["fourteen"] = 14;m["fifteen"] = 15;
    m["sixteen"] = 16;m["seventeen"] = 17;m["eighteen"] = 18;m["nineteen"] = 19;m["twenty"] = 20;
    m["thirty"] = 30;m["forty"] = 40;m["fifty"] = 50;m["sixty"] = 60;m["seventy"] = 70;
    m["eighty"] = 80;m["ninety"] = 90;m["hundred"] = 100;m["thousand"] = 1000;m["million"] = 1000000;
}

//因为是局部变量,此处返回值不能使用引用
vector<string> splitstr(const string& str) {
    vector<string> sub;
    string::size_type endpos=string::npos;
    int startpos=0;
    while((endpos=str.find(" ", startpos)) && (endpos!=string::npos)) {
        sub.push_back(str.substr(startpos, endpos-startpos));
        startpos = endpos+1;
    }
    sub.push_back(str.substr(startpos)); //添加最后一个子字符串
    return sub;
} 

int multistr2int(const vector<string>& multistr,const map<string, int>& m) {
    int num=0, part=0;
    int flag=1;
    for (int i=0; i<multistr.size(); i++)
    {
        if (m.at(multistr[i])==-1) {
            flag=-1;
        }
        else if (m.at(multistr[i])==100) {
            part *= 100;
        }
        else if (m.at(multistr[i])==1000) {
            part *= 1000;
            num += part;
            part=0;
        }
        else if (m.at(multistr[i])==1000000) {
            part *= 1000000;
            num += part;
            part=0;
        }
        else {
            part += m.at(multistr[i]);
        }
    }
    num += part;
    num *= flag;
    return num;
}

int  main()
{    
    map<string, int> m;
    printmap(m);
    string str;
    vector<string> multistr;
    while(getline(cin, str) && str.size()!=0) {
        multistr=splitstr(str);
        cout << multistr2int(multistr, m) << endl;
    }
    return 0;
}

你可能感兴趣的:(字符串-英语数字转换器(数据结构基础 第4周))