整体思路为:读入模板时识别所有变量,两边各加两个大括号处理之后,赋值为空串存入unordered_map;读入变量的同时进行处理,两边各加两个大括号,对已存入的进行修改。之后用每个变量遍历模板,寻找并替换即可。
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <unordered_map>
using namespace std;
unordered_map<string, string> mp;
int main()
{
int m, n;
string a[110];
cin>>m>>n;
getchar();
for(int i = 0 ; i < m ; ++i)
{
string temp;
getline(cin, temp);
int begin = 0, end = 0;
while((begin = temp.find("{{ ", begin)) != string::npos)
{
if((end = temp.find(" }}", begin)) == string::npos)
break;
end += 3;
// cout<<end <<" "<< begin<<endl;
mp[temp.substr(begin, end - begin)] = "";
begin += 3;
}
a[i] = temp;
}
for(int i = 0 ; i < n ; ++i)
{
string temp1, temp2, temp3;
getline(cin, temp1);
int k = 0;
if((k = temp1.find(" ", 0)) == string::npos)
{
temp2 = temp1;
temp3 = "";
}
else
{
temp2 = temp1.substr(0, k);
temp3 = temp1.substr(k + 2, temp1.length() - k - 3);
}
temp2 = "{{ "+temp2+" }}";
mp[temp2] = temp3;
}
for(unordered_map<string, string>::iterator it = mp.begin() ; it != mp.end() ; ++it)
{
for(int j = 0 ; j < m ; ++j)
{
int k = 0;
while((k = a[j].find(it->first, k)) != string::npos && k < a[j].length())
{
a[j].replace(k, it->first.length(), it->second);
k += it->first.length();
}
}
}
for(int i = 0 ; i < m ; ++i)
{
cout<<a[i]<<endl;
}
}
来源:CSDN
作者:Sho.Sakurai
链接:https://blog.csdn.net/weixin_41414657/article/details/104267836