-
Notifications
You must be signed in to change notification settings - Fork 0
/
replacer.cpp
93 lines (79 loc) · 3.05 KB
/
replacer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
This file has the implementation of the replacer class functions
*/
#include "replacer.h"
#include<iostream>
#include<fstream>
#include<string>
#include<unordered_map>
using namespace std;
//constructor
replacer::replacer()
{
language = "en"; //Initializes language to English
preserveUnmatched = "false"; //Initializes preserveUnmatched to false
}
//function to replace the placeholders "${namespace:key}"
void replacer::nestedReplace(string& param, int index)
{
unordered_map<string,string> m1;
string line,fileName,key;
size_t index1,index2;
m1.clear(); //clear the map
index1 = param.find(':',index+2);
if(index1 != string::npos)
{
//if place holders is in "${namespace:${string}} ${namespace:key}" pattern
if((index1 > param.find('$',index+2)))
{
return;
}
//for nested replacements of the placeholders
if((param[index1+1]== '$') && (param[index1+2]=='{'))
{
nestedReplace(param,index1+1);
}
index2 = param.find('}', index1);
if(index2 != string::npos)
{
//get the values from the variables file to replace with placeholders
fileName = param.substr(index+2,index1-index-2); //extracts the namespace value from the placeholder to get the variables file name.
ifs.open(language + "\/" + fileName + ".properties"); //opens the file from the respective path based on the language eg: en/colors.properties
while (ifs >> line)
{
//stores the key and value from the variables file in the map
size_t equal = line.find("=");
string key = line.substr(0, equal);
string value = line.substr(equal + 1);
m1[key] = value;
}
//Match the keys to replace in the string
key = param.substr(index1+1,index2-index1-1); //extracts the key from the placeholder
if(m1.find(key) == m1.end())
{
//for unmatched keys
if(preserveUnmatched == "false")
param.replace(index, index2 - index+1, " ");
}
else
{
param.replace(index, index2 - index+1, m1[key]);
}
ifs.close();
}
}
}
void replacer::multipleReplace(string& parameters)
{
size_t index = parameters.find("$");
//parse the string to replace all the placeholders
while (index != string::npos)
{
if (parameters[index + 1] == '{')
{
nestedReplace(parameters,index);
}
index = parameters.find("$",index+1); //get the next placeholder
}
cout<<"\n"<<parameters<<"\n"<<endl; //prints the replaced string.
}