Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way in C# to combine an arbitrary number of strings into a single string

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.

like image 252
Fired from Amazon.com Avatar asked May 07 '15 16:05

Fired from Amazon.com


People also ask

How \r is used in C?

\r (Carriage Return) – We use it to position the cursor to the beginning of the current line. \\ (Backslash) – We use it to display the backslash character.

What is %d and & in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

Which is the correct way to give comment in C?

There are two ways to add comments in C: // - Single Line Comment. /*... */ - Multi-line Comment.

What does the \n mean in C?

For example, \n is an escape sequence that denotes a newline character.


2 Answers

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.

like image 95
Jon Skeet Avatar answered Oct 04 '22 17:10

Jon Skeet


I prefer using string.Join:

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

You can read about string.Join on MSDN

like image 30
dotnetom Avatar answered Oct 04 '22 15:10

dotnetom