什么是聪明的方式来输出n项与(N-1),其间分隔符的列表? [英] What are clever ways to output a list of n items with (n-1) separators inbetween?

查看:133
本文介绍了什么是聪明的方式来输出n项与(N-1),其间分隔符的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,我们有n个元素(N> 0)的数组。

我们想以输出这些元素的列表,在它们之间具有隔板。

一个常用的方法这个问题是:

 的foreach项目
  (
    输出项目
    输出隔离
  )
修剪最后的分隔符
 

不过好像有点乱不得不这样做。

另一种方法是:

 确认至少有一个元素
循环
  (
     输出元
     下一个元素,或休息,如果没有更多的元素
     输出隔离
  )
 

但我不能肯定它会一直工作。

你看其他聪明的方法来做到这一点,例如在C,C ++?

解决方案

 的char *九月=;
对于(i = 0; I<大小; ++ I){
    的printf(%s%S,九月,项目[I]);
    九月=,;
}
 

Let's say that we have an array with n elements (n > 0).

We would like to output a list of those elements, with a separator between them.

A common approach to this problem is:

foreach item
  (
    output item
    output separator
  )
trim last separator

But it seems a bit messy to have to do that.

Another approach would be:

check that there is at least one element
loop
  (
     output element
     next element, or break if no more elements
     output separator
  )

But I am not sure that it will always work.

Do you see other clever ways to do that, for example in C, C++?

解决方案

char *sep = "";
for (i = 0; i < size; ++i) {
    printf("%s%s", sep, item[i]);
    sep = ", ";
}

这篇关于什么是聪明的方式来输出n项与(N-1),其间分隔符的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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