题目就不贴了。
这道题难度不是很大,只要会使用string的find函数和replace函数或者正则表达式就能将问题解决。总的来说这两种方式的思路都是先匹配"{{ }}",然后替换里面的值,下面是两种方法的代码:
如果你不会正则表达式,可以参考我的另一篇博客正则表达式入门
正则表达式版
#include <bits/stdc++.h>
using namespace std;
void getKeyValue(string s,string& key,string& value)
{
int space = s.find(" ");
key = s.substr(0,space);
value = s.substr(space+2,s.size()-space-3);
}
string Replace(string s,map<string,string>& mp)
{
string ans="",target;
regex double_brace("\\{\\{ (.*?) \\}\\}");
smatch match_result;
while(1)
{
if(regex_search(s,match_result,double_brace))
{
target = match_result[0].str();
ans += match_result.prefix();
ans += mp[target.substr(3,target.size()-6)];
s = match_result.suffix();
}
else
{
ans += s;
break;
}
}
return ans;
}
int main(int argc, char const *argv[])
{
int n,m;
string temp,s,key,value;
map<string,string> mp;
cin >> n >> m;
cin.ignore();
for(int i = 0;i < n; i++)
{
getline(cin,temp);
s += temp + "\n";
}
for(int i = 0;i < m; i++)
{
getline(cin,temp);
getKeyValue(temp,key,value);
mp[key] = value;
}
cout << Replace(s,mp) << endl;
return 0;
}
find + replace版
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<windows.h>
using namespace std;
int n,m;
vector<string> lines;
string str;
map<string,string> dict;
void getKeyValue(string s,string& key,string& value)
{
int space = s.find(" ");
key = s.substr(0,space);
value = s.substr(space+2,s.size()-space-3);
}
void Replace()
{
for(int i = 0;i < lines.size(); i++)
{
string& s = lines[i];
int begin = 0;
while(1)
{
int left = s.find("{{ ",begin);
if(left == -1)
break;
int right = s.find(" }}",begin);
string name = s.substr(left+3,right - 1 - (left + 3) + 1);
s = s.replace(left,name.size() + 6,dict[name]);
begin = left + dict[name].size();
}
}
}
int main()
{
cin >> n >> m;
cin.ignore();
for(int i = 0;i < n; i++)
{
getline(cin,str);
lines.push_back(str);
}
string line,key,value;
for(int i = 0;i < m; i++)
{
getline(cin,line);
getKeyValue(line,key,value);
dict[key] = value;
}
Replace();
for(int i = 0;i < lines.size(); i++)
{
cout << lines[i] << endl;
}
}