String
constructorUsually a string
constructor call is not needed. But the C# language has many string
constructors. These create strings from characters and arrays.
One possible use for a string
constructor is creating a string
containing one char
repeated many times. Another is converting a char
array into a string
.
Char
array exampleTo begin, we show how to create a string
from a char
array. The string
constructor in C# is useful for creating strings from various data sources.
char
array. It is at first empty, but we assign 3 characters to its memory.string
with a string
constructor from an existing char
array. The string
"abc" results from a 3-char
array.string
constructor is an ideal way to convert a char
array to a string
.string
, you usually should just modify an existing string
or use a string
literal.using System; // Part 1: create char array. char[] charArray = new char[3]; charArray[0] = 'a'; charArray[1] = 'b'; charArray[2] = 'c'; // Part 2: create string from array. string exampleString = new string(charArray); Console.WriteLine(exampleString); Console.WriteLine(exampleString == "abc");abc True
Suppose we want to create a whitespace string
with a space repeated 100 times. This is easy with the string
constructor—no large string
literal is needed.
string
can be used like any other in a C# program.using System; // Create new string of repeated characters. string exampleString = new string('a', 10); Console.WriteLine(exampleString); Console.WriteLine(exampleString == "aaaaaaaaaa");aaaaaaaaaa True
Char
array, rangeSuppose we have a char
array, but want to create a string
from just part of it. We can use another string
constructor and specify and offset or a length.
string
.using System; // Create new string from range of characters in array. char[] charArray = new char[6]; charArray[0] = 'a'; charArray[1] = 'B'; charArray[2] = 'c'; charArray[3] = 'D'; charArray[4] = 'e'; charArray[5] = 'F'; string exampleString = new string(charArray, 0, 3); Console.WriteLine(exampleString); Console.WriteLine(exampleString == "aBc");aBc True
We can use the string
constructors as an impressive optimization. Sometimes, we can entirely replace StringBuilder
with a char
array.
string
constructor that repeats characters N times to a string
literal. In a benchmark, the literal is faster.String
constructors are occasionally useful. We used the 3 string
constructors in C# that are not unsafe. And we found ways string
conversions can be optimized.