我非常喜欢 sprintf in c++? 中给出的答案但这仍然不是我要找的东西。
我想创建一个带有占位符的常量字符串,比如
const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout";
然后使用可替换参数构建字符串,例如:
sprintf(url, LOGIN_URL, protocol, server); //coding sprintf from long ago memory, please ignore
但如果可以的话,我真的想远离 C 字符串。
stringbuilder() 方法要求我将我的常量字符串分块并在我想使用它们时组装它们。这是一个很好的方法,但我想做的更简洁。
最佳答案
Boost format library听起来像您正在寻找的内容,例如:
#include <iostream>
#include <boost/format.hpp>
int main() {
int x = 5;
boost::format formatter("%+5d");
std::cout << formatter % x << std::endl;
}
或者对于您的具体示例:
#include <iostream>
#include <string>
#include <boost/format.hpp>
int main() {
const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout";
const std::string protocol = "http";
const std::string server = "localhost";
boost::format formatter(LOGIN_URL);
std::string url = str(formatter % protocol % server);
std::cout << url << std::endl;
}
关于c++ - 带有 C++ 字符串类的 sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7583976/