Concatenate string collection into one string with separator and enclosing characters

前端 未结 1 1868
北荒
北荒 2021-01-27 16:49

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         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 17:47

    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]".

    0 讨论(0)
提交回复
热议问题