问题
I need a function to escape some characters inside a std::string
and so i made this:
static void escape(std::string& source,const std::vector<std::string> & toEscape, const std::string& escape){
//for each position of the string
for(auto i = 0; i < source.size(); ++i){
// for each substring to escape
for(const auto & cur_to_escape : toEscape){
// if the current position + the size of the current "to_escape" string are less than the string size and it's equal to the substring next of the i'th position
if(i + cur_to_escape.size() < source.size() && source.substr(i, cur_to_escape.size()) == cur_to_escape){
// then for each char of the current "to_escape", escape the current character with the "escape" string given as parameter
/*
* source = asd
* toEscape = {"asd"}
* escape = \
* -> asd -> \asd -> \a\sd -> \a\s\d
* */
for(auto z = 0; z < cur_to_escape.size(); ++z){
source.insert(i, escape);
i+=escape.size();
}
}
}
}
}
and to test it i've used this:
int main() {
std::string s = "need to escape \" , \\ and \n .";
std::cout<<s;
escape(s, {"\n", "\\", "\""}, "\\");
std::cout<<"\n\n final string: "<<s;
}
and the output is
final string: need to escape \" , \\ and \
.
and so the \n
is not been escaped as intended... and i can't find the problem... any guesses?
回答1:
“and so the \n is not been escaped as intended” Yes, it is: the new-line character is there, as expected. If you expect an 'n'
character, you are wrong. '\n'
is a convention used to represent the "invisible" character New-Line (NL
).
Here's a cleaner way to write the same thing (try it):
std::string escape(const char* src, const std::set<char> escapee, const char marker)
{
std::string r;
while (char c = *src++)
{
if (escapee.find(c) != escapee.end())
r += marker;
r += c; // to get the desired behavior, replace this line with: r += c == '\n' ? 'n' : c;
}
return r;
}
//...
std::string r = escape("\"this\" is a test\nthis is the second line", { '"', '\n' }, '\\');
回答2:
This is working code, but it is not optimal and can be made faster but probably also bigger.
void escape(std::string& source, const std::vector<std::string>& to_escape, const std::string& escape) {
// for each substring to escape
for (const auto &e : to_escape) {
auto pos = source.find(e);
while (pos != std::string::npos) {
auto to_replace = escape+e;
if (e=="\n") to_replace = escape+"n";
else if (e=="\t") to_replace = escape+"t";
source.replace(pos, e.size(), to_replace);
const auto old_pos = pos;
pos = source.find(e, old_pos + to_replace.size());
}
}
}
Live Code
来源:https://stackoverflow.com/questions/61035929/function-to-escape-some-characters-for-c-string