单词转换程序:将一个文本中的单词按照另一个文本的转换规则,替换成另外一个文本中的单词.并且开头字母大写;
#include "iostream"
#include "vector"
#include "list"
#include "map"
#include "set"
#include "string"
#include "algorithm"
#include "utility"
#include "fstream"
#include "sstream"
using namespace std;
map<string,string> build_map(ifstream&map_file)
{
map<string, string> Trans;
string line, word;
while (map_file>>word&&getline(map_file,line))
{
Trans[word] = line.substr(1);//去掉空格
}
return Trans;
}
string convert(const map<string,string>&Trans_map,const string &word)
{
auto pos = Trans_map.find(word);
return (pos == Trans_map.cend() ? word : pos->second);
}
void word_transform(string filename1,string filename2)
{
ifstream map_file(filename1), input_file(filename2);
auto trans_map = build_map(map_file);
string word, line;
while (getline(input_file,line))//获取输入内容
{
istringstream is(line);
string line2;
while (is >> word)//读入输入的单词
line2 += convert(trans_map, word)+" ";
if (!(ispunct(line2[0]) || isdigit(line2[0])))
line2[0] = toupper(line2[0]);
cout <<line2<< endl;
}
}
int main()
{
word_transform("Text1.txt", "Text2.txt");
return 0;
}
输入:
where r you
y dont u send me a pic
k thk 18r
“I am the king of wor
转换规则:
k okay
y why
r are
u you
pic picture
thk thanks!
18r later