Home
C#
string.Join Examples
This page was last reviewed on Feb 18, 2024.
Dot Net Perls
Join. The C# string.Join method combines many strings into one. It receives 2 arguments: an array (or IEnumerable) and a separator string.
This method 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.
Argument 1 The first argument to string.Join is the separator string. Here we use a comma as the separator.
Argument 2 The words array, which is an array of 3 string literals, is the source of the elements to join together.
using System; string[] words = { "one", "two", "three" }; // Call the Join method and print the resulting string. var result = string.Join(",", words); Console.WriteLine(result);
one,two,three
HTML. We can use string.Join to generate HTML. Often with HTML we need a separating tag or element. Join helps because it does not insert the separating tag at the end.
Step 1 The strings are concatenated with Join into 3 lines of markup in HTML, separated by the BR tag.
Step 2 We write the resulting HTML to a file, and then can test it in a web browser to see the rendered HTML.
using System; using System.IO; var items = new string[] { "Line 1", "Line 2", "Final line" }; // Step 1: join with break element in HTML. string html = string.Join("<br/>\r\n", items); // Step 2: write to text file. File.WriteAllText("test.html", html); Console.WriteLine("DONE");
DONE
StringBuilder. We can replace code that appends strings in loops with a single call to string.Join. The string.Join method is often faster in addition to being simpler.
StringBuilder
Part 1 We call a method that combines strings with Join. A delimiter is not added onto the end.
Part 2 This version of the method combines strings with StringBuilder and its Append method. A delimiter is added to the end.
Note The end delimiter is added to the StringBuilder, but it is later removed. We call TrimEnd to remove the end delimiter.
String TrimEnd, TrimStart
using System; using System.Text; class Program { static void Main() { string[] animals = { "bird", "cat", "dog", "frog" }; // Part 1: use method that calls string.Join. Console.WriteLine(CombineA(animals)); // Part 2: use StringBuilder method. Console.WriteLine(CombineB(animals)); } static string CombineA(string[] arr) { return string.Join(",", arr); } static string CombineB(string[] arr) { StringBuilder builder = new StringBuilder(); foreach (string s in arr) { builder.Append(s).Append(","); } return builder.ToString().TrimEnd(new char[] { ',' }); } }
bird,cat,dog,frog bird,cat,dog,frog
List. We can use string.Join with a List. This example includes the System.Collections.Generic namespace. Here a List is instantiated with 3 string literals in it.
List
String Literal
Argument 1 The first argument to string.Join is the separator string—it will be placed between each item.
Argument 2 The second argument is a reference to the List that contains the elements we want to join.
Return 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 a List if we do not have a string array available.
using System; using System.Collections.Generic; // Create a List of 3 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);
cat*dog*rat
Exceptions. String.Join can throw 3 different exceptions. The first 2 exceptions (ArgumentNullException, ArgumentOutOfRangeException) are often possible.
Tip This code shows what happens when you call string.Join with null parameters. It will throw an ArgumentNullException.
Exception
using System; class Program { static void Main() { try { string bug = string.Join(null, null); // Null arguments are bad } catch (Exception ex) { Console.WriteLine(ex); } } }
System.ArgumentNullException: Value cannot be null. Parameter name: value
A benchmark. We test the general performance of string.Join. This method appears to have excellent performance. We see that string.Join performs well—often better than loops.
Benchmark
Version 1 We concatenate all the strings and delimiters together with the string.Join method.
Version 2 This version of the code concatenates the strings with StringBuilder, and leaves the trailing delimiter.
foreach
Result With .NET 5 for Linux, the string.Join method finishes its task in less time. We should prefer string.Join when possible.
using System; using System.Diagnostics; class Program { 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. } const int _max = 1000000; static void Main() { string[] arr = { "one", "two", "three", "four", "five" }; var s1 = Stopwatch.StartNew(); // Version 1: use string.Join. for (int i = 0; i < _max; i++) { if (CombineA(arr).Length == 0) { return; } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use StringBuilder. for (int i = 0; i < _max; i++) { if (CombineB(arr).Length == 0) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }
58.42 ns string.Join 122.52 ns StringBuilder, Append, ToString
Result note. When we call Join, we do not get an ending delimiter on the result. The separator only is placed between elements—this is desired in some programs, but not in others.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 18, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.