Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert an array of characters into a string in C#?
Converting an array of characters into a string is a common operation in C#. There are multiple approaches to accomplish this, each suitable for different scenarios.
Syntax
Following is the syntax for converting a character array to string using the string constructor −
string str = new string(charArray);
Following is the syntax using the string constructor with range specification −
string str = new string(charArray, startIndex, length);
Using String Constructor
The simplest way to convert a character array to a string is using the string constructor that accepts a character array −
using System;
class Program {
static void Main() {
char[] ch = new char[5];
ch[0] = 'T';
ch[1] = 'r';
ch[2] = 'i';
ch[3] = 'c';
ch[4] = 'k';
// converting to string
string str = new string(ch);
Console.WriteLine("Converted string: " + str);
}
}
The output of the above code is −
Converted string: Trick
Using String Constructor with Range
You can also specify a starting index and length to convert only a portion of the character array −
using System;
class Program {
static void Main() {
char[] ch = {'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd'};
// Convert first 5 characters
string str1 = new string(ch, 0, 5);
Console.WriteLine("First 5 characters: " + str1);
// Convert last 5 characters
string str2 = new string(ch, 5, 5);
Console.WriteLine("Last 5 characters: " + str2);
// Convert entire array
string str3 = new string(ch);
Console.WriteLine("Complete string: " + str3);
}
}
The output of the above code is −
First 5 characters: Hello Last 5 characters: World Complete string: HelloWorld
Using String.Join Method
Another approach is using the String.Join() method with an empty separator −
using System;
class Program {
static void Main() {
char[] ch = {'C', '#', ' ', 'i', 's', ' ', 'f', 'u', 'n'};
string str = String.Join("", ch);
Console.WriteLine("Using String.Join: " + str);
}
}
The output of the above code is −
Using String.Join: C# is fun
Comparison of Methods
| Method | Performance | Use Case |
|---|---|---|
| String Constructor | Fastest | Complete array conversion |
| String Constructor with Range | Fast | Partial array conversion |
| String.Join("") | Slower | When you need more flexibility |
Conclusion
Converting a character array to string in C# is most efficiently done using the string constructor. Use the parameterized constructor when you need to convert only a specific portion of the array, and consider String.Join() for more complex scenarios.
