[英]How do I concatenate a vector of strings in c++ with boost?
I have a vector of strings, like this: 我有一个向量字符串,像这样:
{"abc"}{"def"}{"ghi"}
I want to concatenate them into a single string, with a separator like "-". 我想将它们连接成一个字符串,并使用“-”之类的分隔符。
Is there a concise (pretty) way of doing this without using a typical for loop? 是否有一种简洁(漂亮)的方法无需使用典型的for循环? I have c++03 and boost available to me. 我可以使用c ++ 03和boost。
Sure, boost provides a convenient algorithm for achieving what you are trying to do. 当然,boost为实现您要执行的操作提供了一种便捷的算法。 In higher level languages you may have spotted a join function. 在更高级别的语言中,您可能已经发现了连接功能。 Boost provides an equivalent algorithm in the join function. Boost在join函数中提供了等效的算法。
#include <boost/algorithm/string/join.hpp>
using namespace std;
string data[] = {"abc","def","ghi"};
const size_t data_size = sizeof(data) / sizeof(data[0]);
vector<string> stringVector(data, data + data_size);
string joinedString = boost::algorithm::join(stringVector, "-");
Just for reference, there is currently a proposal for std::join
, which you can check out here . 仅供参考,目前有std::join
的建议,您可以在此处查看 。
But since you have boost available, you can use boost::algorithm::join
, which takes a sequence of strings and a separator, like so: 但是,由于您有可用的增强功能,因此可以使用boost::algorithm::join
,它需要一个字符串序列和一个分隔符,如下所示:
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/join.hpp>
int main() {
std::vector<std::string> words;
words.push_back("abc");
words.push_back("def");
words.push_back("ghi");
std::string result = boost::algorithm::join(words, "-");
std::cout << result << std::endl;
}
Prints: 印刷品:
abc-def-ghi
Another option using only the STL is: 仅使用STL的另一种选择是:
std::ostringstream result;
if (my_vector.size()) {
std::copy(my_vector.begin(), my_vector.end()-1,
std::ostream_iterator<string>(result, "-"));
result << my_vector.back();
}
return result.str()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.