Join multiple strings with delimiter in C#
This article illustrates the different techniques to join multiple strings with delimiter in C#.
1. Using String.Join() method
A simple solution to join multiple strings with a delimiter is using the String.Join() method. It concatenates members of the specified list with the specified separator, as shown below. Note that the String.Join() method is available with .NET 4.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> words = new List<string>() { "A", "B", "C" }; string str = string.Join(", ", words.ToArray()); Console.WriteLine(str); // A, B, C } } |
2. Using StringBuilder
Before .NET 4, you can use StringBuilder to join multiple strings together with a delimiter. The idea is to iterate over the list and append each encountered element to StringBuilder separated by a delimiter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Text; using System.Collections.Generic; public static class Extensions { public static string Join(this List<string> words, char delim) { if (words.Count == 0) { return string.Empty; } StringBuilder sb = new StringBuilder(); foreach (string item in words) { sb.Append(item).Append(delim); } return sb.ToString().Remove(sb.Length - 1); } } public class Example { public static void Main() { List<string> words = new List<string>() { "A", "B", "C" }; string str = words.Join(','); Console.WriteLine(str); // A,B,C } } |
The above code will append the delimiter on all items except the last. Here’s an alternative solution to achieve the same:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Text; using System.Collections.Generic; public static class Extensions { public static string Join(this List<string> words, string delim) { StringBuilder sb = new StringBuilder(); string sep = string.Empty; foreach (string item in words) { sb.Append(sep).Append(item); sep = delim; } return sb.ToString(); } } public class Example { public static void Main() { List<string> words = new List<string>() { "A", "B", "C" }; string str = words.Join(", "); Console.WriteLine(str); // A, B, C } } |
That’s all about joining multiple strings together with delimiter in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)