算法加入例如字符串数组 [英] Algorithm for joining e.g. an array of strings

查看:129
本文介绍了算法加入例如字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道有一段时间,什么加盟字符串数组一个不错的,干净的解决方案可能是什么样子。 例如:我有[阿尔法,测试版,伽玛],并想加入串为一体,以逗号分隔 - 阿尔法,贝塔,伽玛

I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".

现在我知道,大多数编程语言提供了某种形式的连接方法为这个的。我只是想知道如何将这些可能实现。 当我把入门课程,我常常试图单干,但从来没有发现一个满意的算法。一切都显得相当混乱,问题是,你可以不通过阵列只是循环,串联的字符串,如你想补充太多了逗号(之前或之后的最后一个字符串)。 我不想要查询条件循环。我真的不希望添加的第一个或最后一个字符串之前/循环后(我想这也许是最好的方式?)。

Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented. When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string). I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).

有人能告诉我一个优雅的解决方案?或者告诉我到底为什么不能有什么更优雅?

Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?

推荐答案

最优雅的解决方案,我发现这样的问题是这样的(伪code)

The most elegant solution i found for problems like this is something like this (in pseudocode)

separator = ""
foreach(item in stringCollection)
{
    concatenatedString += separator + item
    separator = ","
}

您只需运行的循环和周围的分离,第二次设置之后。因此,在第一时间将不会被添加。这不是干净,因为我想它是这样我还是会加评论,但它比一个更好,如果语句或加入外循环的第一个或最后一个项目。

You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.

这篇关于算法加入例如字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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