HomeSearch

C# String Join Examples

Use the string.Join method. Join combines an array of strings into one string with a separator.
Join. The string.Join method combines many strings into one. It receives two arguments: an array (or IEnumerable) and a separator string.IEnumerableStrings
When we call Join, it places the separator between every element of the collection in the returned string. The separator is not added to the start or end of the result.
First example. We combine string elements from an array into a new, single string with dividing characters. This example will produce the output with separating commas.Array

Note: Join is a static method. We need no string instance to call it. We just use the string class.

Static

Main: The first line in Main creates a string array with 3 elements. The second 2 lines display the result of String.Join.

Tip: You can use uppercase or lowercase String. You do not need to specify a string instance.

Parameters: You can specify 4 arguments on string.Join. The last two are the startIndex and the count.

Overload
C# program that joins strings using System; class Program { static void Main() { string[] arr = { "one", "two", "three" }; // "string" can be lowercase. Console.WriteLine(string.Join(",", arr)); // ... "String" can be uppercase. Console.WriteLine(String.Join(",", arr)); } } Output one,two,three one,two,three
HTML. We use string.Join to generate HTML. Often with HTML you need a separating tag or element. Join helps because it doesn't insert the separating tag at the end.

Next: The strings are concatenated with Join into four lines of markup in HTML, separated by the BR tag.

C# program that joins HTML strings using System; class Program { static void Main() { // Problem: combine these words into lines in HTML string[] dinosaurs = new string[] { "Aeolosaurus", "Deinonychus", "Jaxartosaurus", "Segnosaurus" }; // Solution: join with break tag. string html = string.Join("<br/>\r\n", dinosaurs); Console.WriteLine(html); } } Output Aeolosaurus<br/> Deinonychus<br/> Jaxartosaurus<br/> Segnosaurus
StringBuilder. We can replace confusing code that appends strings in loops with much simpler string.Join code. The string.Join method is often much faster in addition to being simpler.

Here: CombineA combines strings with Join. CombineB combines strings with StringBuilder and its Append method.

Info: The methods concatenate each string into a single string with separators. CombineB uses ToString and TrimEnd to get the result.

ToString: StringBuilderTrimEnd, TrimStart
C# program that combines strings with Join using System; using System.Text; class Program { static void Main() { string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" }; Console.WriteLine(CombineA(catSpecies)); Console.WriteLine(CombineB(catSpecies)); } /// <summary> /// Combine strings with commas. /// </summary> static string CombineA(string[] arr) { return string.Join(",", arr); } /// <summary> /// Combine strings with commas. /// </summary> static string CombineB(string[] arr) { StringBuilder builder = new StringBuilder(); foreach (string s in arr) { builder.Append(s).Append(","); } return builder.ToString().TrimEnd(new char[] { ',' }); } } Output Aegean,Birman,Main Coon,Nebulung Aegean,Birman,Main Coon,Nebulung
StringBuilder comparison. String.Join is different from appending many strings together in a loop, such as with StringBuilder. It does not insert the delimiter at the end.

Instead: Join() only inserts the delimiter in between the strings. This is usually (but not always) desirable.

Exceptions. String.Join can throw three different exceptions. The first two exceptions (ArgumentNullException, ArgumentOutOfRangeException) are often possible.ArgumentExceptionOutOfMemoryException

Tip: This code shows what happens when you call string.Join with null parameters. It will throw an ArgumentNullException.

Exception
C# program that throws exception on Join using System; class Program { static void Main() { try { string bug = string.Join(null, null); // Null arguments are bad } catch (Exception ex) { Console.WriteLine(ex); } } } Output System.ArgumentNullException: Value cannot be null. Parameter name: value
List. It is possible to join a List generic. This example includes the System.Collections.Generic namespace. Here a List is instantiated with three string literals in it.ListString Literal

Next: We call the string.Join<string> method. The first argument indicates the separator. The second is a reference to the List.

Returns: The method returns a joined string containing the separator. It works the same way as the array version.

Tip: This method eliminates copies. It is preferable to use this version on your List if you do not have an array of your strings handy.

C# program that joins List of strings using System; using System.Collections.Generic; class Program { static void Main() { // Create a List of three strings. var list = new List<string>() { "cat", "dog", "rat" }; // Join the strings from the List. string joined = string.Join<string>("*", list); // Display. Console.WriteLine(joined); } } Output cat*dog*rat
Benchmark. We test the general performance of string.Join. Join does not appear to cause a severe slowdown. We see that string.Join performs well—often better than loops.

Info: The methods return different strings. CombineA does not have a comma at the end of its result, while CombineB does.

StringBuilderForeach

Thus: We find that using the TrimEnd method to remove the comma makes CombineB slower.

Data used in benchmark: C# string[] arr = { "one", "two", "three", "four", "five" }; Methods that were benchmarked, 1000000 iterations: C# static string CombineA(string[] arr) { return string.Join(",", arr); } static string CombineB(string[] arr) { var builder = new System.Text.StringBuilder(); foreach (string s in arr) { builder.Append(s).Append(","); } return builder.ToString(); // Has ending comma [difference] } Output string.Join: 157 ms [faster] StringBuilder Append method: 270 ms Required Join method results Input: one two three Output: one*two*three
A summary. Join is an important operation on the string type. It simplifies certain common operations on string arrays. It is helpful when StringBuilder is not needed.
We created comma-separated values and generated HTML source. And we found string.Join has excellent performance for common usages.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls