我们首先来看这样一个场景: 某人很懒, 写信的时候, 经常用简写的形式代替完整的形式, 比如:
9494--->Yes, it is!
asap--->as soon as possible
sb--->se bi
....
现在, 要写一套程序, 将这些简单的直接还原为原始的完整形式。 其实, 思路是很自然的, 对简写信中的每一个单词进行判断, 如果需要转化, 则转化, 如果不需要转化, 则不用转化。 这个需不需要, 取决于当前单词是否在map中, 好吧, 我们来看看编程模型吧:
步骤一: 建立固定的转换规格文档default.txt, 其内容如下:
9494 Yes, it is!
asap as soon as possible
sb se bi
r are
y you
步骤二: 在simpleLetter.txt中写信, 假设内容为:
i think y r a sb
9494
please reply it asap
步骤三:写代码来转化:
#pragma warning(disable : 4786)
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
typedef map<string, string> mapSS;
typedef map<string, string>::const_iterator mapSSIT;
// 转换规则
mapSS createMap(ifstream &mapFile)
{
mapSS mp;
string key;
string value;
while(mapFile >> key && getline(mapFile, value)) // 其实value不再是一整行了
{
if(value.size() < 1)
{
exit(1);
}
mp[key] = value.substr(1); // 好好理解一下这句话
}
return mp;
}
// 转换单词
const string& change(const string &s, const mapSS &mp)
{
mapSSIT it = mp.find(s);
if(it == mp.end())
{
return s;
}
return it->second;
}
// 转换信件
int main()
{
ifstream inMP("default.txt");
ifstream inLetter("simpleLetter.txt");
if(!inMP || !inLetter)
{
return 1;
}
mapSS mp = createMap(inMP);
string line;
while(getline(inLetter, line))
{
stringstream isstr(line); // 我们又和stringstream见面了, 好亲切
string word;
bool isFirstWord = true;
while(isstr >> word)
{
if(isFirstWord)
{
isFirstWord = false;
}
else
{
cout << " ";
}
cout << change(word, mp);
}
cout << endl;
}
return 0;
}
程序的结果为:
i think you are a se bi
Yes, it is!
please reply it as soon as possible
当然, 需要指出的是, 如果在简写信件里面有标点符号, 那么很可能对程序造成影响。 上面程序仅仅是考虑了一些简单的情况。
再一次, 我们看到了map的强大用途。