有哪些巧妙的方法可以输出 n 个项目的列表,其中之间有 (n-1) 个分隔符?

发布于 2024-10-04 22:02:01 字数 465 浏览 0 评论 0原文

假设我们有一个包含 n 个元素的数组 (n > 0)。

我们希望输出这些元素的列表,它们之间有分隔符。

解决这个问题的常见方法是:

foreach item
  (
    output item
    output separator
  )
trim last separator

但必须这样做似乎有点混乱。

另一种方法是:

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

但我不确定它是否永远有效。

您是否看到其他聪明的方法来做到这一点,例如在 C、C++ 中?

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++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

百合的盛世恋 2024-10-11 22:02:01
char *sep = "";
for (i = 0; i < size; ++i) {
    printf("%s%s", sep, item[i]);
    sep = ", ";
}
char *sep = "";
for (i = 0; i < size; ++i) {
    printf("%s%s", sep, item[i]);
    sep = ", ";
}
满意归宿 2024-10-11 22:02:01
for (i = 0; i < n; ++i) switch(i) {
    default: output_separator();
    case 0: output_item(i);
}

或对此的变体。我实在想不出还有什么办法可以不重复output_item(i)

for (i = 0; i < n; ++i) switch(i) {
    default: output_separator();
    case 0: output_item(i);
}

or variations on this. I can't really think of how else not to repeat output_item(i).

清浅ˋ旧时光 2024-10-11 22:02:01

有时:

output item 0
for item 1 to n
{
    output separator
    output item
}

更短。

Sometimes:

output item 0
for item 1 to n
{
    output separator
    output item
}

is shorter.

过期以后 2024-10-11 22:02:01

由于它被标记为与语言无关,我认为有必要指出,某些语言具有内置功能,可以让您甚至不用考虑这个问题。以这段 python 代码为例:

>>> print string.join(['list', 'of', 'some', 'words'], ', ')
list, of, some, words

As it is tagged as language-agnostic I think it's important to point out, that some languages have built-in features to spare you from even thinking about this problem. Take this python code for example:

>>> print string.join(['list', 'of', 'some', 'words'], ', ')
list, of, some, words
酷到爆炸 2024-10-11 22:02:01

可能的 C++ 解决方案:

http://groups.google.com/group/comp.lang.c++ /msg/a746a588cedfa44b

总结:写一个infix_ostream_iterator,它与ostream_iterator基本相同,只不过“separator”参数实际上是分隔符,而不是后缀到每一个项目。那么用法将是:

std::copy(first, last, infix_ostream_iterator<ItemType>(output, separator));

A possible C++ solution:

http://groups.google.com/group/comp.lang.c++/msg/a746a588cedfa44b

Summary: write an infix_ostream_iterator, which is basically the same as ostream_iterator except that the "separator" parameter really is a separator, not a suffix to every item. Usage would then be:

std::copy(first, last, infix_ostream_iterator<ItemType>(output, separator));
弥繁 2024-10-11 22:02:01

无论好坏,我使用计数循环,

for (i = 0; i < num_items; i++){
  if (i > 0) output separator;
  output item[i];
}

我确信这是老式的投反对票诱饵,但它有效。

如果有人想告诉我这效率低下,我已经准备好火焰了吗;-)

For better or worse, I use counted loops, with

for (i = 0; i < num_items; i++){
  if (i > 0) output separator;
  output item[i];
}

I'm sure this is downvote-bait for being old fashioned, but it works.

If anybody wants to tell me it's inefficient, boy do I have a flame ready ;-)

一人独醉 2024-10-11 22:02:01

这个版本避免了任何额外的分支:(

int i = 0;
goto skip_delim;
do {
               put_delim();
   skip_delim: put_el(i++);
} while (i < size);

对于那些害怕goto的人,可以使用Duff设备中的方法来编写它)

This version avoids any additional branches:

int i = 0;
goto skip_delim;
do {
               put_delim();
   skip_delim: put_el(i++);
} while (i < size);

(For those who are afraid of goto, it can be written using approach from Duff's device)

三生殊途 2024-10-11 22:02:01

Haskell 中的“第一次检查”习惯用法:

intersperse :: Show a => String -> [a] -> String
intersperse _ [] = ""
intersperse s (x:xs) = show x ++ concatMap ((s ++) . show) xs

它的用法如下:

*Main> intersperse "," [1,2,3]
"1,2,3"
*Main> intersperse "," [1]
"1"
*Main> intersperse ";" [1,2]
"1;2"
*Main> intersperse "," []
""

The "first check" idiom in Haskell:

intersperse :: Show a => String -> [a] -> String
intersperse _ [] = ""
intersperse s (x:xs) = show x ++ concatMap ((s ++) . show) xs

It's used like so:

*Main> intersperse "," [1,2,3]
"1,2,3"
*Main> intersperse "," [1]
"1"
*Main> intersperse ";" [1,2]
"1;2"
*Main> intersperse "," []
""
宛菡 2024-10-11 22:02:01

我总是使用第一项检查习惯用法。这是java中的代码:

List<Object> list;
if (list.size() > 0) {
   put(list.get(0));
}
for(int i = 1; i < list.size(); i++) {
   putSeparator();
   put(list.get(i));                                
}

I always use first item check idiom. Here is the code in java:

List<Object> list;
if (list.size() > 0) {
   put(list.get(0));
}
for(int i = 1; i < list.size(); i++) {
   putSeparator();
   put(list.get(i));                                
}
吲‖鸣 2024-10-11 22:02:01
for i in items.length-1; do
   output item; output separator
output last item
for i in items.length-1; do
   output item; output separator
output last item
梦晓ヶ微光ヅ倾城 2024-10-11 22:02:01

在 Common Lisp 中,只要您可以对分隔符进行硬编码,它就非常简单。

(defun return-delimited-list (list &optional stream)
  (format stream "~{~A~^, ~}" list))

调用时,它返回一个由 list 中的元素组成的字符串,以“,”分隔(最后一个元素后面不跟任何内容除外)。好吧,如果输入一个输出流,它会将其打印到流中,恰好“nil”意味着“没有流,只返回一个字符串”。

In Common Lisp, it's bordering on simple, as long as you can hard-code the separator.

(defun return-delimited-list (list &optional stream)
  (format stream "~{~A~^, ~}" list))

When called, this returns a string consisting of the elements in list, separated by ", " (except for the last element not being followed by anything). Well, if fed an output stream, it prints it to the stream, it just so happens that 'nil' means "No stream, just return a string".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文