c++ - 如何将多个字符串附加到一个以逗号分隔的字符串?

标签 c++ string stl

<分区>

我有以下列表:

vector<string> mylist;

我想创建一个新字符串,其中 mylist 中的所有字符串都用逗号分隔,多年来我一直在编写丑陋的代码来检查我是否在 vector 中的最后一个字符串中以了解我是否应该添加逗号还是不是。

代码看起来像这样:

for(unsigned int i=0;i<mylist.size(); i++)
{
    outstring+=mylist[i];
    if(i<mylist.size()-1) // Avoiding the last comma
    {
        outstring+=",";
    }
}

是否有避免 if 语句的技巧,也许是一些使用 STL 的算法/迭代器技巧?

谢谢

最佳答案

使用boost::algorithm::join():

#include <boost/algorithm/string/join.hpp>
...
string outstring = boost::algorithm::join(mylist, ",");

或者,您可以使用(实际上非​​常难看):

stringstream  s;
copy(mylist.begin(), mylist.end(), ostream_iterator<string>(s, ","));
string outstring = s.str();  // still with the trailing delimiter ","
outstring.pop_back();        // pop back the last ","

关于c++ - 如何将多个字符串附加到一个以逗号分隔的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23325072/

相关文章:

c++ - 英特尔 TBB 链接和 RPATH

c++ - 如何为 MacOS 安装库 "iberty"?

python - 当我在 python+jupyter 中使用 print 时仍然显示引号

c++ - 从子类访问模板类成员时找不到标识符错误

java - Java中用外国字符替换英文字符的方法?

c# - 使用 List<string>.Any() 查找字符串是否包含项目以及查找匹配项目?

c++ - 类型衰减 STL 迭代器

c++ - 如何测试序列生成器是否会生成预期的项目?

c++ - std::unique 可以用来确定自定义类的对象是否具有相同的值吗?

c++ - 在 C++ 中生成 AST