sprintf与c++字符串类
sprintf with C++ string class
我真的很喜欢sprintf在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格式库听起来像你正在寻找的,例如:
#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;
}
看一下:Boost Format