Different Ways to Convert Char Array to String in C#
We have given a character array arr and the task is to convert char array to string str in C#.
Input: arr = [s, t, r, i, n, g] Output: string Input: arr = [G, e, e, k, s, F, o, r, G, e, e, k, s] Output: w3wiki
In order to do this task, we have the following methods:
Method 1:
Using string() Method: The String class has several overloaded constructors which take an array of characters or bytes. Thus it can be used to create a new string from the character array.
Syntax:
string str = new string(character_array);
Example:
C#
// C# program to convert the // char array to string using System; using System.Text; public class GFG{ static string getString( char [] arr) { // string() is a used to // convert the char array // to string string s = new string (arr); return s; } static void Main( string [] args) { // given character array char [] arr = { 'G' , 'e' , 'e' , 'k' , 's' , 'F' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' }; // function calling string str = getString(arr); // printing output Console.WriteLine(str); } } |
Output:
w3wiki
Method 2:
Using Join() Method: This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. Thus it can be used to create a new string from the character array.
Syntax:
string str = string.Join("", character_array);
Example:
C#
// C# program to convert the // char array to string using System; using System.Text; public class GFG{ static string getString( char [] arr) { // String.Join() is a used to // convert the char array // to string string s = string .Join( "" , arr); return s; } static void Main( string [] args) { // given character array char [] arr = { 'G' , 'e' , 'e' , 'k' , 's' , 'F' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' }; // function calling string str = getString(arr); // printing output Console.WriteLine(str); } } |
Output:
w3wiki
Method 3:
Using Concat() Method: This method is used to concatenate one or more instances of String or the String representations of the values of one or more instances of Object. Thus it can be used to create a new string from the character array.
Syntax:
string str = string.Concat(character_array);
Example:
C#
// C# program to convert the // char array to string using System; using System.Text; public class GFG{ static string getString( char [] arr) { // String.Concat() is a used to // convert the char array // to string string s = string .Concat(arr); return s; } static void Main( string [] args) { // given character array char [] arr = { 'G' , 'e' , 'e' , 'k' , 's' , 'F' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' }; // function calling string str = getString(arr); // printing output Console.WriteLine(str); } } |
Output:
w3wiki
Contact Us