简体   繁体   English

C ++ Sanitize字符串函数

[英]C++ Sanitize string function

I need to build my own sanitize function for the following chars: 我需要为以下字符构建自己的清理函数:

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

I want to make sure that the following code will do the trick with no side effects: 我想确保以下代码可以完成没有副作用的技巧:

#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(), "\0", "");
    stringValue.replace(stringValue.begin(), stringValue.end(), "\x1A", "");
}

int main()
{
    std::string stringValue = "This is a test string with 'special //characters\n";

    std::cout << stringValue << std::endl;

    sanitize(stringValue);

    std::cout << stringValue << std::endl;
}

This code is not working. 此代码无效。 Error: 错误:

    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

Original code here 原始代码在这里

See comment to my post as to why your replace calls are incorrect. 请参阅我的帖子评论,为什么您的replace呼叫不正确。 "\\0" has another problem: "\\0"还有另一个问题:

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

\\0 marks the end of a C string, so it will try to replace an empty string with an empty string. \\0标记C字符串的结尾,因此它将尝试用空字符串替换空字符串。 It seems you are removing \\n, \\r, \\0 and CTRL-Z , in which case you can use the erase-remove idiom instead for these: 看来你正在删除\\n, \\r, \\0 and CTRL-Z ,在这种情况下你可以使用erase-remove惯用法代替:

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 || '\0' == c || '\x1A' == c;
            }
        ),
        stringValue.end()
    );
}

See it working here . 看到它在这里工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM