C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Convert: The string constructor is an ideal way to convert a char array to a string.
Convert Char Array, StringTip: To create a new string, you usually should just modify an existing string or use a string literal.
String LiteralC# program that uses string constructor, char array
using System;
class Program
{
static void Main()
{
// Create new string from char array.
char[] charArray = new char[3];
charArray[0] = 'a';
charArray[1] = 'b';
charArray[2] = 'c';
string exampleString = new string(charArray);
Console.WriteLine(exampleString);
Console.WriteLine(exampleString == "abc");
}
}
Output
abc
True
Here: We repeat the letter "A" 10 times. The resulting string can be used like any other in a C# program.
PadRight: This is much simpler than using PadRight or PadLeft methods to create repeated characters.
PadRight, PadLeftC# program that uses repeated characters
using System;
class Program
{
static void Main()
{
// Create new string of repeated characters.
string exampleString = new string('a', 10);
Console.WriteLine(exampleString);
Console.WriteLine(exampleString == "aaaaaaaaaa");
}
}
Output
aaaaaaaaaa
True
Here: We start at index 0, and continue until we have taken 3 chars. We turn the first 3 chars of the array into a string.
Substring: This string constructor is the equivalent of Substring, but acts on char arrays.
SubstringC# program that uses char array, range for string
using System;
class Program
{
static void Main()
{
// 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");
}
}
Output
aBc
True
String constructors: C#
unsafe public String(char*);
public String(char[]);
unsafe public String(sbyte*);
public String(char, int);
unsafe public String(char*, int, int);
public String(char[], int, int);
unsafe public String(sbyte*, int, int);
unsafe public String(sbyte*, int, int, Encoding);
Tip: There is no difference between calling "new String" and "new string". The uppercase first letter makes no difference.
And: This is most useful for sorting algorithms or other lower-level operations on strings in C# programs.
StringBuilder