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: GeeksForGeeks
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#
using System;
using System.Text;
public class GFG{
static string getString( char [] arr)
{
string s = new string (arr);
return s;
}
static void Main( string [] args)
{
char [] arr = { 'G' , 'e' , 'e' , 'k' ,
's' , 'F' , 'o' , 'r' , 'G' , 'e' ,
'e' , 'k' , 's' };
string str = getString(arr);
Console.WriteLine(str);
}
}
|
Output:
GeeksForGeeks
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#
using System;
using System.Text;
public class GFG{
static string getString( char [] arr)
{
string s = string .Join( "" , arr);
return s;
}
static void Main( string [] args)
{
char [] arr = { 'G' , 'e' , 'e' , 'k' ,
's' , 'F' , 'o' , 'r' , 'G' , 'e' ,
'e' , 'k' , 's' };
string str = getString(arr);
Console.WriteLine(str);
}
}
|
Output:
GeeksForGeeks
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#
using System;
using System.Text;
public class GFG{
static string getString( char [] arr)
{
string s = string .Concat(arr);
return s;
}
static void Main( string [] args)
{
char [] arr = { 'G' , 'e' , 'e' , 'k' ,
's' , 'F' , 'o' , 'r' , 'G' , 'e' ,
'e' , 'k' , 's' };
string str = getString(arr);
Console.WriteLine(str);
}
}
|
Output:
GeeksForGeeks