有两个文件context.txt和words.conf,请尝试将他们合并成为一段文字,并打印出来。
这两个文件内容如下:
context.txt
“并不是每个人都需要$(qunar)自己的粮食,$(flight.1)每个人都需要做自己穿的$(flight.2),我们说着别人发明的$(hotel),使用别人发明的数学......我们一直在$(tuan)别人的成果。使用人类的已有经验和知识$(travel.1)来进行,是一件$(travel.2)的事情”
word.conf
flight=也不是:衣服
qunar=种植
hotel=语言
tuan=使用
travel=发明创造:很了不起
#include <string>
#include <fstream>
using namespace std;
void combine(string &str, multimap<string, string>m)
{
int index = 1;
char in[20];
multimap<string, string>::iterator iter;
for (iter=m.begin(); iter != m.end(); iter++)
{
if (m.count(iter->first) == 1)
{
index = 1;
string searchString = "$(" + iter->first + ")";
string replaceString = iter->second;
string::size_type pos = 0;
while ((pos = str.find(searchString, pos)) != string::npos)
{
str.replace(pos, searchString.size(), replaceString);
pos++;
}
}
else
{
sprintf(in,"%d", index);
string searchString = "$(" + iter->first + "." + string(in) + ")";
string replaceString = iter->second;
string::size_type pos = 0;
while ((pos = str.find(searchString, pos)) != string::npos)
{
str.replace(pos, searchString.size(), replaceString);
pos++;
}
index++;
}
}
}
int main()
{
multimap<string, string>m;
//m.insert(make_pair("flight", "也不是"));
//m.insert(make_pair("flight", "衣服"));
//m.insert(make_pair("hotel", "语言"));
//multimap<string, string>::iterator iter;
//for (iter = m.begin(); iter != m.end(); iter++)
//{
// printf("%d\n", m.count(iter->first));
// printf("%s\n", iter->first.c_str());
// printf("%s\n", iter->second.c_str());
//}
ifstream context("d:\\context.txt");
ifstream config("d:\\word.conf");
char buffer[4096];
memset(buffer, 0, 4096);
string temp;
char *p = NULL;
context.read(buffer, 4096);
printf("%s\n", buffer);
string str = buffer;
string key;
string value;
memset(buffer, 0, 4096);
while (config.getline(buffer, 4096))
{
p = strtok(buffer, "=:");
if (p != NULL)
{
key = p;
}
while (p != NULL)
{
printf("%s\n", p);
p = strtok(NULL, "=:");
if (p != NULL)
{
value = p;
m.insert(make_pair(key, value));
}
}
memset(buffer, 0, 4096);
}
//char *p = NULL;
//string key;
//string value;
//FILE *fContext = fopen("d:\\context.txt", "r");
//if (fContext == NULL)
//{
// return -1;
//}
//char buffer[4096];
//memset(buffer, 0, 4096);
//int ret = fread(buffer, 4096, 1, fContext);
//printf("%s\n", buffer);
//string str = buffer;
//FILE *fConfig = fopen("d:\\word.conf", "r");
//if (fConfig == NULL)
//{
// return -1;
//}
//while(fgets(buffer, 4096, fConfig) != NULL)
//{
// p = strtok(buffer, "=:");
// if (p != NULL)
// {
// key = p;
// }
// while (p != NULL)
// {
// printf("%s\n", p);
// p = strtok(NULL, "=:");
// if (p != NULL)
// {
// value = p;
// }
// m.insert(make_pair(key, value));
// }
// memset(buffer, 0, 4096);
//}
//string str = "$(flight.1)每个人都需要做自己穿的$(flight.2),我们说着别人发明的$(hotel)";
combine(str, m);
printf("%s\n", str.c_str());
return 0;
}