【问题标题】:C++ Sanitize string functionC++ 清理字符串函数
【发布时间】:2015-12-11 10:20:55
【问题描述】:

我需要为以下字符构建自己的清理功能:

', ", \, \n, \r, \0 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(), "\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;
}

此代码不起作用。错误:

    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

原码here

【问题讨论】:

  • 当然,反斜杠应该是第一个被替换的……然后是其他的。已更正。
  • 是的,它没有比第一步更进一步......看到参数正在使用错误的字符串长度来替换。
  • 您能否解释一下,您认为是针对哪个std::basic_string::replace 函数签名?

标签: c++ string


【解决方案1】:

请参阅我的帖子评论,了解为什么您的 replace 调用不正确。 "\0"还有一个问题:

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

\0 标记 C 字符串的结尾,因此它会尝试用空字符串替换空字符串。您似乎正在删除 \n, \r, \0 and CTRL-Z,在这种情况下,您可以使用 erase-remove idiom 来代替这些:

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.

【讨论】:

    猜你喜欢
    • 2011-06-22
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多