为C ++字符串转义一些字符的函数 [英] Function to escape some characters for C++ string

查看:140
本文介绍了为C ++字符串转义一些字符的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

,输出为

final string: need to escape \" , \\ and \
 .

,因此 \n 未能按预期进行转义...而且我找不到问题。 ..有任何猜想吗?

and so the \n is not been escaped as intended... and i can't find the problem... any guesses?

推荐答案

因此\n并未按预期进行转义 是的,它是:换行符如预期的那样存在。如果您期望'n'字符,则您错了。' \n'是用于表示不可见字符换行符( NL )的约定。

"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' }, '\\');

这篇关于为C ++字符串转义一些字符的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆