5

I breezed through the documentation for the string class and didn't see any good tools for combining an arbitrary number of strings into a single string. The best procedure I could come up with in my program is

string [] assetUrlPieces = { Server.MapPath("~/assets/"), 
                             "organizationName/",
                             "categoryName/",
                             (Guid.NewGuid().ToString() + "/"),
                             (Path.GetFileNameWithoutExtension(file.FileName) + "/")
                           };

string assetUrl = combinedString(assetUrlPieces);

private string combinedString ( string [] pieces )
{
    string alltogether = "";
    foreach (string thispiece in pieces) alltogether += alltogether + thispiece;
    return alltogether; 
}

but that seems like too much code and too much inefficiency (from the string addition) and awkwardness.

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
  • Check out [`string.Concat`](https://msdn.microsoft.com/en-us/library/0wkb0y3w(v=vs.110).aspx) – juharr May 07 '15 at 16:35

5 Answers5

17

If you want to insert a separator between values, string.Join is your friend. If you just want to concatenate the strings, then you can use string.Concat:

string assetUrl = string.Concat(assetUrlPieces);

That's marginally simpler (and possibly more efficient, but probably insignificantly) than calling string.Join with an empty separator.

As noted in comments, if you're actually building up the array at the same point in the code that you do the concatenation, and you don't need the array for anything else, just use concatenation directly:

string assetUrl = Server.MapPath("~/assets/") +
    "organizationName/" + 
    "categoryName/" +
    Guid.NewGuid() + "/" +
    Path.GetFileNameWithoutExtension(file.FileName) + "/";

... or potentially use string.Format instead.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Some Jon Skeet suggested to just use plus instead of building array and iterating over it :) http://stackoverflow.com/questions/10341188/string-concatenation-using-operator as it is compiled into `String.Concat` anyway... – Alexei Levenkov May 07 '15 at 16:42
  • @AlexeiLevenkov: True, but I'm assuming that in the OP's *real* situation, the array is coming from elsewhere... – Jon Skeet May 07 '15 at 16:45
15

I prefer using string.Join:

var result = string.Join("", pieces);

You can read about string.Join on MSDN

dotnetom
  • 24,551
  • 9
  • 51
  • 54
  • This is the fastest and easiest way to do it. Nitpick: Use `string.Empty` maybe. – Bas May 07 '15 at 16:35
  • Side note: this (along with `StringBuilder` and `String.Concat` for small number of strings) is right way to combine multiple strings when they are just text. For url/path cases it is preferable to use `Uri`, `UriBuilder`, `Path` types... – Alexei Levenkov May 07 '15 at 16:38
  • @JonSkeet Learning everyday :) – Bas May 07 '15 at 16:39
4

You want a StringBuilder, I think.

var sb = new StringBuilder(pieces.Count());
foreach(var s in pieces) {
    sb.Append(s);
}
return sb.ToString();

Update

@FiredFromAmazon.com: I think you'll want to go with the string.Concat solution offered by others for

  1. Its sheer simplicity
  2. Higher performance. Under the hood, it uses FillStringChecked, which does pointer copies, whereas string.Join uses StringBuilder. See http://referencesource.microsoft.com/#mscorlib/system/string.cs,1512. (Thank you to @Bas).
DWright
  • 9,258
  • 4
  • 36
  • 53
  • This is almost how `string.Join` is implemented, however it is optimized if it knows the number of strings beforehand to calculate the length of the buffer, http://referencesource.microsoft.com/#mscorlib/system/string.cs,06d13c9cb8b83f5d. No use in reimplementing it. – Bas May 07 '15 at 16:37
  • @Bas: thanks, updated construction of StringBuilder with the count of Strings in the pieces array to show use of length of buffer as per your remark. – DWright May 07 '15 at 16:40
  • @FiredFromAmazon.com see my update above about using string.Concat – DWright May 07 '15 at 16:50
3

string.Concat is the most appropriate method for what you want.

var result = string.Concat(pieces);

Unless you want to put delimiters between the individual strings. Then you'd use string.Join

var result = string.Join(",", pieces); // comma delimited result.
James
  • 7,343
  • 9
  • 46
  • 82
juharr
  • 31,741
  • 4
  • 58
  • 93
0

A simple way to do this with a regular for loop: (since you can use the indices, plus I like these loops better than foreach loops)

   private string combinedString(string[] pieces)
   {
    string alltogether = "";
    for (int index = 0; index <= pieces.Length - 1; index++) {
        if (index != pieces.Length - 1) {
             alltogether += string.Format("{0}/" pieces[index]);
        }
    }
    return alltogether;
jt25617
  • 21
  • 6