自动替换stringstream中的字符

时间:2016-12-13 08:44:09

标签: c++ string replace stream

在我用字符串内容填充后,我正在寻找一种替换ostringstream中的字符的方法,但是只有一些非常低效的解决方案提取string,修改它和把它放回ostringstream

现在我想知道在添加字符串时是否有自动替换这些字符的方法。 E.g。

ostringstream my_json;
my_json << replace_singlequotes;  # modify the stringsteam once
my_json << "{'this':";
my_json << " 'is valid JSON'}";
std::cout << my_json.str();

output:
{"this": "is valid JSON"}

您是否可以为ostringstream编写一个类似于std::hex等格式修饰符的自定义过滤器,它会在将给定字符串输入流之前对其进行修改?

或者除了在ostringstream上运行std::replace()之外,还有其他方法可以替换my_json.str()中的字符,如其他问题和howtos中所建议的那样吗?

1 个答案:

答案 0 :(得分:2)

您可以使用用户定义的操纵器来实现此目的。请参阅以下示例:

#include <iostream>
#include <sstream>

class replace_singlequotes {
    friend std::ostream& operator<<(std::ostream &, const replace_singlequotes &);
private:
    std::string str;
public:
    replace_singlequotes(std::string);
};

replace_singlequotes::replace_singlequotes(std::string str) {
    this->str = str;
}

std::ostream& operator<<(std::ostream& os, const replace_singlequotes &value) {
    std::string result = value.str;
    for (int i = 0; i < result.length(); i++) {
        if (result.at(i) == '\'') {
            result.at(i) = '\"';
        }
    }
    os << result;
    return os;
}

int main() {
    std::ostringstream my_json;
    my_json << replace_singlequotes("{'this': 'is valid JSON'}");
    std::cout << my_json.str() << std::endl;
    return 0;
}

输出如下:

{"this": "is valid JSON"}

更新:以下是使用运算符重载概念执行此操作的另一种方法:

#include <iostream>
#include <sstream>

class String {
private:
    std::string value;
public:
    String operator=(const std::string value);
    friend std::ostream & operator<< (std::ostream &out, String const &str);
    friend std::istream& operator>>(std::istream& in, String &str);
};

std::ostream & operator<<(std::ostream &out, const String &str) {
    std::string result = str.value;
    for (int i = 0; i < result.length(); i++) {
        if (result.at(i) == '\'') {
            result.at(i) = '\"';
        }
    }
    out << result;
    return out;
}

std::istream& operator>>(std::istream& in, String &str) {
    in >> str.value;
    return in;
}

String String::operator=(const std::string value) {
    this->value = value;
    return *this;
}

int main() {
    std::stringstream out;
    String str;

    str = "{'this': 'is valid JSON'}";
    out << str;

    std::cout<<out.str();
    return 0;
}

注意:

  • 上述程序也会产生与{"this": "is valid JSON"}
  • 相同的输出
  • 这里的优点是您可以使用insertion operator (<<) 直接用双引号替换单引号。
  • 上面的代码片段使用了运算符重载的概念 最初的例子是使用用户定义的操纵器。

如果您想使用replace_singlequotes作为操纵者而且    如果您想将重载概念与此相结合,我建议    您按照以下步骤操作:

  1. 在...中声明一个名为boolean的{​​{1}}标记 类。
  2. 设为replace_singlequotes
  3. 检查标志值是否为static并确定您是否拥有 在插入运算符(true/false)的重载主体中用双引号替换单引号。