C++Sanitize字符串函数

C++ Sanitize string function

本文关键字:函数 字符串 C++Sanitize      更新时间:2023-10-16

我需要为以下字符构建自己的消毒函数:

', ", , n, r,  and CTRL-Z

我想确保以下代码将做的技巧没有副作用:

#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include <iomanip>
#include <algorithm>    
void sanitize (std::string &stringValue)
{
    stringValue.replace(stringValue.begin(), stringValue.end(), "\", "\\");
    stringValue.replace(stringValue.begin(), stringValue.end(), "'", "'");
    stringValue.replace(stringValue.begin(), stringValue.end(), """, "\"");
    stringValue.replace(stringValue.begin(), stringValue.end(), "n", "");
    stringValue.replace(stringValue.begin(), stringValue.end(), "r", "");
    stringValue.replace(stringValue.begin(), stringValue.end(), "", "");
    stringValue.replace(stringValue.begin(), stringValue.end(), "x1A", "");
}
int main()
{
    std::string stringValue = "This is a test string with 'special //charactersn";
    std::cout << stringValue << std::endl;
    sanitize(stringValue);
    std::cout << stringValue << std::endl;
}

此代码不起作用。错误:

    terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_M_replace
      1 
      1 This is a test string with 'special //characters

此处的原始代码

请参阅我的帖子中关于为什么您的replace调用不正确的评论。""还有另一个问题:

stringValue.replace(stringValue.begin(), stringValue.end(), "", "");

标记C字符串的结束,因此它将尝试用空字符串替换空字符串。似乎您正在删除n, r, and CTRL-Z,在这种情况下,您可以使用擦除-删除习语来代替这些:

void sanitize(std::string &stringValue)
{
    // Add backslashes.
    for (auto i = stringValue.begin();;) {
        auto const pos = std::find_if(
            i, stringValue.end(),
            [](char const c) { return '' == c || ''' == c || '"' == c; }
        );
        if (pos == stringValue.end()) {
            break;
        }
        i = std::next(stringValue.insert(pos, ''), 2);
    }
    // Removes others.
    stringValue.erase(
        std::remove_if(
            stringValue.begin(), stringValue.end(), [](char const c) {
                return 'n' == c || 'r' == c || '' == c || 'x1A' == c;
            }
        ),
        stringValue.end()
    );
}

看到它在这里工作。