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

て烟熏妆下的殇ゞ 提交于 2021-01-27 17:54:16

问题


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

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


回答1:


In this case you don't want to use string.Concat(), you want to use 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:

"cat#dog#perls"

(assuming, of course, that theArray contains those values)




回答2:


Try like this :

String.Join("#", catdogperls)



回答3:


You're looking for String.Join(), which takes a collection and a separator.




回答4:


Use string.Join(), it allows you to specify the separator you want between each string - it's been in the framework since v2.0.

In later versions of the framework it was extended so that you could pass in an IEnumerable instead of just an array.



来源:https://stackoverflow.com/questions/19624855/how-do-i-insert-a-separator-when-concatenating-a-string-in-c

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