简体   繁体   English

在C#中连接字符串时如何插入分隔符?

[英]How do I insert a separator when concatenating a string in C#?

I have a list of strings and I am concatenating it to flatten out the list by using the method seen here on DotNetPerls, http://www.dotnetperls.com/string-concat 我有一个字符串列表,我正在使用DotNetPerls上的方法, http: //www.dotnetperls.com/string-concat连接它以使列表变平

My question is...in their List example where their output is "catdogperls" (see toward the bottom of the webpage, just before the Summary) how do I insert a # sign as a separator between "catdogperls" such that it becomes "cat#dog#perls"? 我的问题是......在他们的List示例中,他们的输出是“catdogperls”(在摘要之前看到网页底部)如何在“catdogperls”之间插入#符号作为分隔符,使其成为“猫#狗#皮尔斯“?

In this case you don't want to use string.Concat() , you want to use string.Join() . 在这种情况下,你不想使用string.Concat() ,你想使用string.Join() This accepts a separator and an array of strings to join by that separator. 这接受分隔符和要由该分隔符连接的字符串数组。 For example: 例如:

var joined = string.Join("#", theArray);

This would place the string value in joined : 这会将字符串值放在joined

"cat#dog#perls"

(assuming, of course, that theArray contains those values) (当然,假设theArray包含这些值)

试试这样:

String.Join("#", catdogperls)

你正在寻找String.Join() ,它采用一个集合和一个分隔符。

Use string.Join() , it allows you to specify the separator you want between each string - it's been in the framework since v2.0. 使用string.Join() ,它允许您指定每个字符串之间所需的分隔符 - 它自v2.0以来一直在框架中。

In later versions of the framework it was extended so that you could pass in an IEnumerable instead of just an array. 在框架的更高版本中,它被扩展,以便您可以传入IEnumerable而不仅仅是数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM