Convert List of Chars to a String in C#
This post will discuss how to convert a List of Chars to a String in C#.
1. Using String.Join() Method
The shortest and most idiomatic way to append characters of a list to a single string separated by a delimiter is using the String.Join method. The following code example demonstrates the usage of the String.Join method for concatenating characters of a list with a comma as a separator between each character.
|
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<char> chars = new List<char> { 'A', 'B', 'C' }; string s = string.Join(",", chars); Console.WriteLine(s); // A,B,C } } |
2. Using String Class Constructor
Another option for converting the list of characters to a string is to use the String constructor, which can accept a list of characters and initialize a new instance of the String object with the corresponding characters, without any delimiter. The following code example demonstrates this.
|
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<char> chars = new List<char> { 'A', 'B', 'C' }; string s = new string(chars.ToArray()); Console.WriteLine(s); // A,B,C } } |
3. Using String.Concat() Method
Finally, you can also use the convenience method String.Concat() to concatenate the characters of a list separated by an empty string, as demonstrated below:
|
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<char> chars = new List<char> { 'A', 'B', 'C' }; string s = string.Concat(chars); Console.WriteLine(s); // A,B,C } } |
That’s all about converting a List of Chars to a String 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 :)