模拟题,小细节比较多
1.用getline()
读入一整行的时候要先用getchar()
处理之前cin
读剩下的的回车(cin
不读回车)
2.getline()
读入的一行存到vector
中处理起来更方便
3.题目中的变量名没有空格,而值是用双引号括起来的包含空格的字符串,所以变量名可以用cin
读,值不能用cin
读。
4.值可以用getchar()
读,顺便过滤双引号(要用到转义字符),然后把变量名和对应的值存到哈希表中,方便后面替换。
5.遍历vector中的每一行,枚举时注意{{
两个左括号后面还有空格,所以从i+3
开始枚举
6.哈希表会自动把不存在的键值设为空,直接输出即可。
C++代码
#include <iostream>
#include <cstring>
#include <unordered_map>
#include <vector>
using namespace std;
int n, m;
unordered_map<string, string> vars;
vector<string> strs;
int main()
{
cin >> n >> m;
getchar(); //过滤cin读剩下的回车
while(n -- )
{
string str;
getline(cin, str);
strs.push_back(str);
}
while(m -- )
{
string key, value;
cin >> key; //变量名不含空格,可以直接cin读
char c; //变量值含空格和双引号,用getchar()读
while(c = getchar(), c != '\"'); //过滤第一个引号之前的内容
while(c = getchar(), c != '\"') value += c;
vars[key] = value; //存入哈希表
}
for(auto &str : strs) //遍历vetor中的每一行
{
for(int i = 0; i < str.size();)
if(i + 1 < str.size() && str[i] == '{' && str[i + 1] == '{') //如果需要替换变量
{
int j = i + 3;
string key;
while(str[j] != ' ' || str[j + 1] != '}' || str[j + 2] != '}') //没有到结尾的话
key += str[j ++ ]; //读取模板中的变量
cout << vars[key]; //哈希表替换模板中的值
i = j + 3; //处理完之后要跳过空格和两个右括号
}
else cout << str[i ++ ]; //不需要替换变量,直接输出模板原内容
cout << endl;
}
return 0;
}
有个小问题:while(str[j] != ‘ ‘ || str[j + 1] != ‘}’ && str[j + 2] != ‘}’)。的第2⃣️个应该也是||,望周知
多谢提醒,已修正。