Convert char array to string in C#
This post will discuss how to convert char array to string in C#.
1. Using string constructor
The standard solution to convert the character array into a string is using the String class constructor. The string class has a constructor which takes a character array as a parameter and initializes a new instance of the String class with the corresponding characters. The following example instantiates a string from a character array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { char[] chars = {'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'}; string s = new string(chars); Console.WriteLine(s); // some string } } |
The String constructor is overloaded to accept a character array as an argument, along with the starting position and length.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { char[] chars = {'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'}; string s = new string(chars, 5, chars.Length - 5); Console.WriteLine(s); // string } } |
2. Using String.Join Method
Another option is using the String.Join method to concatenate elements of an array with a separator. The following code example demonstrates the usage of the String.Join method for concatenating characters using an empty string as a separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { char[] chars = {'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'}; string s = string.Join(string.Empty, chars); Console.WriteLine(s); // some string } } |
3. Using String.Concat Method
A better alternative to concatenate the members of a character array without any delimiters is with the convenience method String.Concat(). For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { char[] chars = {'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'}; string s = string.Concat(chars); Console.WriteLine(s); // some string } } |
That’s all about converting char array to 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 :)