【问题标题】:Splitting string in specific format which was created from int vector以特定格式拆分从 int 向量创建的字符串
【发布时间】:2014-04-21 18:07:59
【问题描述】:

我写了一个程序,它从 int 的向量中创建逗号分隔的字符串,如下所示:

std::vector<unsigned int> Vec;
Vec.push_back(50);
Vec.push_back(60);
Vec.push_back(10);
Vec.push_back(20);
Vec.push_back(30);
Vec.push_back(2);
Vec.push_back(1);

std::stringstream lineNumString;
lineNumString.str(std::string());
lineNumString.clear();

std::copy(Vec.begin(), Vec.end(), std::ostream_iterator<unsigned int>(lineNumString, ","));

std::string lineString(lineNumString.str());
lineString = lineString.substr(0, lineString.length()-1);

std::cout << std::endl << lineString;

如果你看到上面程序的输出是:

         `50,60,10,20,30,2,1`

但我想以某种不同的格式更改我的输出。我想在一行上有最多三个数字,下一行有下一个数字。如下:

50,60,10,
20,30,2,
1

我尝试从Vec 创建子向量,并尝试使用它们创建不同的字符串。然后我尝试拆分lineString,然后使用这些字符串。 请让我知道是否有更好的方法来实现最终输出? 我正在使用VS2010。我也可以使用 BOOST 功能。

谢谢。

【问题讨论】:

    标签: c++ string visual-studio-2010 boost split


    【解决方案1】:

    经典循环方式:

    #include <vector>
    #include <iostream>
    #include <sstream>
    #include <iterator>
    
    int main()
    {
      std::vector<unsigned int> Vec;
      Vec.push_back(50);
      Vec.push_back(60);
      Vec.push_back(10);
      Vec.push_back(20);
      Vec.push_back(30);
      Vec.push_back(2);
      Vec.push_back(1);
    
    
      for(auto it = Vec.begin(); it != Vec.end();)
      {
        std::cout << *it++;
    
        if(it != Vec.end())
          std::cout << ",";
    
        if((it - Vec.begin()) % 3 == 0)
          std::cout << std::endl;
      }
    
    
      return 0;
    }
    

    Boost.spirit 方式:

    #include <boost/config/warning_disable.hpp>
    #include <boost/spirit/include/karma.hpp>
    #include <boost/spirit/include/phoenix_core.hpp>
    #include <boost/spirit/include/phoenix_operator.hpp>
    
    #include <iostream>
    #include <vector>
    #include <string>
    
    namespace karma = boost::spirit::karma;
    
    int main()
    {
      std::vector<unsigned int> v = {50, 60, 10, 20, 30, 2, 1};
    
      using karma::int_;
      using karma::eol;
      using karma::duplicate;
      using karma::generate;
    
      std::string out;
      std::back_insert_iterator<std::string> it(out);
    
      generate(it, int_ << "," << *(int_ << "," << int_ << "," << duplicate[ &int_ << eol << int_ << ","]), v);
    
      out[out.size() - 1] = 0;
      std::cout << out << std::endl;
    
      return 0;
    }
    

    duplicate 的小技巧:它重复属性int_,这是强制性的,因为谓词&amp; 消耗它,以便知道我们是否显示行尾(eol)。

    【讨论】:

    • 谢谢。但是有什么方法可以在不循环向量的情况下做到这一点?
    • Boost 精神可以在这里使用...查看我的帖子的编辑!
    猜你喜欢
    • 2021-09-29
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多