【问题标题】:How to concatenate strings with space into one string with STL in c++ [duplicate]如何在c ++中使用STL将带有空格的字符串连接成一个字符串[重复]
【发布时间】:2014-01-08 02:54:53
【问题描述】:

给定一个字符串向量 ["one", "two", "three"]。

问题>如何转换成“一二三”?

我知道手动执行循环的方法,想知道是否 STL 函数有一个更简单的方法。

//根据我应该使用accumulate的建议更新

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

struct BindTwoStrings
{
    string operator()(const string& s1, const string& s2) const {
        return s1.empty() ? s2 : s1 + " " + s2;
    }    
};

int main()
{    
   vector<string> vecString {"one", "two", "three"};   
   string ret2;   

   ret2 = accumulate(vecString.begin(), vecString.end(), ret2, 
           [] (const string& s1, const string& s2) -> string { 
              return s1.empty() ? s2 : s1 + " " + s2; });
   cout << "ret2:\"" << ret2 << "\"" << endl;

   string ret;
   ret = accumulate(vecString.begin(), vecString.end(), ret, BindTwoStrings());

   cout << "ret:\"" << ret << "\"" << endl;
   return 0;
}

【问题讨论】:

标签: c++ stl


【解决方案1】:

使用std::stringstream,您可以这样做:

std::stringstream ss;
const int v_size = v.size();
for(size_t i = 0; i < v_size; ++i)  // v is your vector of string
{
  if(i != 0)
    ss << " ";
  ss << v[i];
}
std::string s = ss.str();

【讨论】:

    【解决方案2】:

    你可以使用std::accumulate():

    std::string concat = std::accumulate(std::begin(array) + 1, std::end(array), array[0],
        [](std::string s0, std::string const& s1) { return s0 += " " + s1; });
    

    【讨论】:

    • @P0W: 这将有一个前导空格,后跟一系列未分隔的字符串...
    • @DietmarKühl,啊,抱歉,一开始似乎没有给我空间,现在我想起来很奇怪。
    • @DietmarKühl 啊,是的,积累总是让我感到困惑
    • @DietmarKühl,你能检查我的更新帖子,看看我的解决方案是否有效吗?
    • 这行得通,但速度慢得要命。 std::ostringstream 在性能上要好得多。
    【解决方案3】:

    您可以使用std::ostream_iterator

    std::vector< std::string > vs{ "one", "two", "three" };
    
    std::ostringstream result_stream;
    std::ostream_iterator< std::string > oit( result_stream, " " );
    std::copy( vs.begin(), vs.end(), oit );
    
    std::string result = result_stream.str();
    

    http://ideone.com/VfxWbd

    如果您想要字符串中的结果,请使用std::ostringstream 作为输出迭代器。

    【讨论】:

    • vs为空时需要修剪尾随空格
    • @P0W 你如何指定别人的问题的要求?无论如何,只需参考重复问答的答案,如果结果 not 为空,则会删除尾随空格。
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多