CCF 201509-3 模板生成系统-正则表达式

    题目就不贴了。

    这道题难度不是很大,只要会使用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;
	}
	
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值