給定一個字典,通過查找這個字典,替換給定的字符串中的中文爲英文

描述:第一對START和END中給定的是字典

        第二對START和END是給定字符串


輸入:

START

hello nihao

yes shi

like xihuan

world shijie

gril nvhai

END

START

i'm a nvhai!

i xihuan shijie.

nihao

END


輸出:

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;
}


《完》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章