转义C++字符串的某些字符的函数



我需要一个函数来转义std::string中的一些字符,所以我做了这个:

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 -> asd -> asd 
* */
for(auto z = 0; z < cur_to_escape.size(); ++z){
source.insert(i, escape);
i+=escape.size();
}
}
}
}
}

为了测试它,我使用了这个:

int main() {
std::string s = "need to escape " , \ and n .";
std::cout<<s;
escape(s, {"n", "\", """}, "\");
std::cout<<"nn final string: "<<s;
}

输出为

final string: need to escape " , \ and 
.

所以n并没有按预期逃脱......而且我找不到问题...有什么猜测吗?

"所以 没有按预期转义">是的,确实如此:换行符在那里,正如预期的那样。如果你期望一个'n'角色,那你就错了。'n'是用于表示"不可见"字符换行符(NL)的约定。

这里有一个更干净的方法来写同样的东西(试试吧):

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 testnthis is the second line", { '"', 'n' }, '\');

这是工作代码,但它不是最佳的,可以做得更快,但也可能更大。

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());
}
}
}

实时代码

最新更新