如何使逗号分隔字符串时,处理最后一个逗号,? [英] How to deal with last comma, when making comma separated string?

查看:964
本文介绍了如何使逗号分隔字符串时,处理最后一个逗号,?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能显示的文件:结果
  不要最后一个号码后打印空间结果
  印刷用逗号列出了C ++


 的#include<矢量>
#包括LT&;&iostream的GT;
#包括LT&;&sstream GT;
#包括LT&;升压/ foreach.hpp>
使用命名空间std;诠释的main()
{
   矢量<诠释> VecInts;   VecInts.push_back(1);
   VecInts.push_back(2);
   VecInts.push_back(3);
   VecInts.push_back(4);
   VecInts.push_back(5);   stringstream的SS;
   BOOST_FOREACH(INT I,VecInts)
   {
      SS<< I<< ,;
   }   COUT<< ss.str();   返回0;
}

本打印出来: 1,2,3,4,5,
不过,我想: 1,2,3,4,5

我怎样才能做到这一点在优雅办法?

我看到有什么我跟优雅是指一些困惑:如如果-条款在我的循环中没有放缓。想象一下,在矢量100.000项!如果这是你所提供的,我宁愿删除最后一个逗号我已经通过循环离开之​​后。


解决方案

这个怎么样:

 的#include<&iostream的GT;
#包括LT&;矢量>
#包括LT&;&算法GT;
#包括LT&;&迭代器GT;
#包括LT&;串GT;
#包括LT&;&sstream GT;诠释的main()
{
   的std ::矢量<&INT GT;伏;   v.push_back(1);
   v.push_back(2);
   v.push_back(3);
   v.push_back(4);
   v.push_back(5);   的std :: ostringstream SS;   性病::复制(v.begin(),v.end() - 1,的std :: ostream_iterator< INT>(SS,));
   SS<< v.back();   性病::法院LT&;< ss.str()&所述;&下; \\ n;
}

无需添加额外的变量,甚至不依赖于刺激!其实,除了要求的循环中没有额外的变量,人们可以说,竟然没有一个循环:)

Possible Duplicates:
Don't print space after last number
Printing lists with commas C++

#include <vector>
#include <iostream>
#include <sstream>
#include <boost/foreach.hpp>
using namespace std;

int main()
{
   vector<int> VecInts;

   VecInts.push_back(1);
   VecInts.push_back(2);
   VecInts.push_back(3);
   VecInts.push_back(4);
   VecInts.push_back(5);

   stringstream ss;
   BOOST_FOREACH(int i, VecInts)
   {
      ss << i << ",";
   }

   cout << ss.str();

   return 0;
}

This prints out: 1,2,3,4,5, However I want: 1,2,3,4,5

How can I achieve that in an elegant way?

I see there is some confusion about what I mean with "elegant": E.g. no slowing down "if-clause" in my loop. Imagine 100.000 entries in the vector! If that is all you have to offer, I'd rather remove the last comma after I have gone through the loop.

解决方案

How about this:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <sstream>

int main()
{
   std::vector<int> v;

   v.push_back(1);
   v.push_back(2);
   v.push_back(3);
   v.push_back(4);
   v.push_back(5);

   std::ostringstream ss;

   std::copy(v.begin(), v.end() - 1, std::ostream_iterator<int>(ss, ", "));
   ss << v.back();

   std::cout << ss.str() << "\n";
}

No need to add extra variables and doesn't even depend on boost! Actually, in addition to the "no additional variable in the loop" requirement, one could say that there is not even a loop :)

这篇关于如何使逗号分隔字符串时,处理最后一个逗号,?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆