Concatenate string collection into one string with separator and enclosing characters

二次信任 提交于 2019-12-20 05:35:34

问题


I have a collection of source strings that I wish to concatenate into one destination string.

The source collection looks as follows:

{ "a", "b", "c" }

I want the output string to be:

abc

But sometimes, I want a separator as well. So for the same input, now the output is to be:

a-b-c

And finally, the input sometimes needs to be enclosed in other characters, in this case [], causing the output to be:

[a]-[b]-[c]

An empty source collection should yield an empty string. How would I go about this?


回答1:


You can do this using the static String.Join() method.

Its basic usage is as such:

string[] sourceData = new[] { "a", "b", "c" };
string separator = "";
var result = string.Join(separator, sourceData);

When you supply an empty separator, the passed values will simply be concatenated to this: "abc".

To separate the source data with a certain string, provide the desired value as the first argument:

string[] sourceData = new[] { "a", "b", "c" };
string separator = "-";
var result = string.Join(separator, sourceData);

Now the string "-" will be inserted between every item in the source data: "a-b-c".

Finally to enclose or modify each item in the source collection, you can use projection using Linq's Select() method:

string[] sourceData = new[] { "a", "b", "c" };
string separator = "-";
result = String.Join(separator, sourceData.Select(s => "[" + s + "]"));

Instead of "[" + s + "]" you'd better use String.Format() to improve the readability and ease of modification : String.Format("[{0}]", s).

Either way, that also returns the desired result: "[a]-[b]-[c]".



来源:https://stackoverflow.com/questions/35139228/concatenate-string-collection-into-one-string-with-separator-and-enclosing-chara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!