将字符串集合连接成一个带分隔符和封闭字符的字符串 [英] Concatenate string collection into one string with separator and enclosing characters

查看:73
本文介绍了将字符串集合连接成一个带分隔符和封闭字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个希望链接成一个目标字符串的源字符串集合。

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

源集合如下所示:

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

我希望输出字符串为:

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?

推荐答案

您可以使用静态 String.Join()方法

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

其基本用法如下:

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

当您提供一个空的分隔符时,传递的值将简单地与此连接: abc

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);

现在字符串- 将为插入到源数据中每个项目之间: abc

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

最后,将项目中的每个项目包含或修改源集合,您可以使用 Linq的 Select使用投影()方法

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 + "]"));

代替 [ + s +] ,最好使用 String.Format() 以提高可读性和易于修改: String.Format( [{0}],s )

无论哪种方式,也都返回期望的结果: [a]-[b]-[ c]

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

这篇关于将字符串集合连接成一个带分隔符和封闭字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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