簡體   English   中英

C ++ Sanitize字符串函數

[英]C++ Sanitize string function

我需要為以下字符構建自己的清理函數:

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

原始代碼在這里

請參閱我的帖子評論,為什么您的replace呼叫不正確。 "\\0"還有另一個問題:

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

\\0標記C字符串的結尾,因此它將嘗試用空字符串替換空字符串。 看來你正在刪除\\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()
    );
}

看到它在這里工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM