您的位置:首页 > 其它

给定一个字典,通过查找这个字典,替换给定的字符串中的中文为英文

2017-03-17 22:09 357 查看
描述:第一对START和END中给定的是字典
第二对START和END是给定字符串

输入:
START
hello nihao
yes shi
like xihuan
world shijie
gril nvhai
END
START
i'm a nvhai!i xihuan shijie.nihaoEND

输出:
i'm a gril!
i like world.
hello

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

const string Start = "START";
const string End = "END";

int main()
{
map<string, string> myMap;
string value;
while (cin >> value){
if (value == Start)
continue;
else if (value == End)
break;
else{
string key;
cin >> key;
myMap[key] = value;
}
}
cin.get();
string linestr;
vector<string> historyBook;
while (getline(cin, linestr)){
if (linestr == Start)
continue;
else if (linestr == End)
break;
else{
historyBook.push_back(linestr);
}
}
int size = historyBook.size();
int line = 0;
while (line < size){
string& curline = historyBook[line];
int strSize = curline.size();
int f = 0, l = 0;
while (l<=strSize){
if (l == strSize || curline[l] == ',' || curline[l] == ' ' || curline[l] == '!' || curline[l] == '.'){ //读完一个单词
char curWord[20];//假设每个单词长度不超过20
strncpy(curWord, (char*)&curline[f], l - f); curWord[l - f] = '\0';//把当前读完的单词放入curWord中
string tmpkey = curWord;
map<string,string>::iterator it=myMap.find(tmpkey);
if (it != myMap.end()){//如果未找到,it==myMap.end()
curline.erase(f, l - f);//删除原来的汉语部分
curline.insert(f, it->second);//在原来的位置插入所替换的英文
f = f + (it->second).size()+1; l = f;
strSize += ((it->second).size() - (it->first).size());//长度改变,所以要更新
}
else{
f = l + 1; l = f;
}
}
else
++l;
}
++line;
}
for (int i = 0; i < historyBook.size(); ++i){
cout << historyBook[i] << endl;
}
system("pause");
return 0;
}


《完》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串 字典 map
相关文章推荐