String Constructor
Initializes a new instance of the String class.
This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.
| Name | Description | |
|---|---|---|
|
String(Char*) | Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters. |
|
String(Char[]) | Initializes a new instance of the String class to the value indicated by an array of Unicode characters. |
|
String(SByte*) | Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers. |
|
String(Char, Int32) | Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times. |
|
String(Char*, Int32, Int32) | Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length. |
|
String(Char[], Int32, Int32) | Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length. |
|
String(SByte*, Int32, Int32) | Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length. |
|
String(SByte*, Int32, Int32, Encoding) | Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object. |
In this section:
Overloaded constructor syntax
Parameters
Exceptions
Which method do I call?
Creating strings
Handling repetitive strings
Examples of instantiating strings:
Using string assignment
Using a character array
Using a portion of a character array and repeating a single character
Using a pointer to a character array
Using a pointer and a range of an array
Using a pointer to a signed byte array
Version information
Overloaded constructor syntax
String constructors fall into two categories: those without pointer parameters, and those with pointer parameters. The constructors that use pointers are not CLS-compliant. In addition, Visual Basic does not support the use of pointers, and C# requires code that uses pointers to run in an unsafe context. For more information, see the unsafe keyword in the C# Reference.
For additional guidance on choosing an overload, see Which method do I call?
Parameters
Here is a complete list of parameters used by String constructors that do not include a pointer parameter. For the parameters used by each overload, see the overload syntax above.
|
Parameter |
Type |
Description |
|---|---|---|
|
value |
Char [] |
An array of Unicode characters. |
|
c |
A Unicode character. |
|
|
startIndex |
The starting position in value of the first character in the new string. Default value: 0 |
|
|
length |
The number of characters in value to include in the new string. Default value: Array.Length |
|
|
count |
The number of times the character c is repeated in the new string. If count is zero, the value of the new object is String.Empty. |
Here is a complete list of parameters used by String constructors that include a pointer parameter. For the parameters used by each overload, see the overload syntax above.
|
Parameter |
Type |
Description |
|---|---|---|
|
value |
Char * -or- SByte * |
A pointer to a null-terminated array of Unicode characters or an array of 8-bit signed integers. If value is null or an empty array, the value of the new string is String.Empty. |
|
startIndex |
The index of the array element that defines the first character in the new string. Default value: 0 |
|
|
length |
The number of array elements to use to create the new string. If length is zero, the constructor creates a string whose value is String.Empty. Default value: Array.Length |
|
|
enc |
An object that specifies how the value array is encoded. Default value: Encoding.Default, or the system's current ANSI code page |
Exceptions
Here's a list of exceptions thrown by constructors that do not include pointer parameters.
|
Exception |
Condition |
Thrown by |
|---|---|---|
|
value is null. |
||
|
startIndex, length, or count is less than zero. -or- The sum of startIndex and length is greater than the number of elements in value. -or- count is less than zero. |
Here's a list of exceptions thrown by constructors that include pointer parameters.
|
Exception |
Condition |
Thrown by |
|---|---|---|
|
value specifies an array that contains an invalid Unicode character. -or- value or value + startIndex specifies an address that is less than 64K. -or- A new String instance could not be initialized from the value byte array because value does not use the default code page encoding. |
All constructors with pointers. |
|
|
value is null. |
||
|
The current process does not have read access to all the addressed characters. -or- startIndex or length is less than zero, value + startIndex cause a pointer overflow, or the current process does not have read access to all the addressed characters. -or- The length of the new string is too large to allocate. |
All constructors with pointers. |
|
|
value, or value + startIndex + length – 1, specifies an invalid address. |
Which method do I call?
|
To |
Call or use |
|---|---|
|
Create a string. |
Assignment from a string literal or an existing string (example) |
|
Create a string from an entire character array. |
|
|
Create a string from a portion of a character array. |
|
|
Create a string that repeats the same character multiple times. |
|
|
Create a string from a pointer to a Unicode or wide character array. |
|
|
Create a string from a portion of a Unicode or wide character array by using its pointer. |
|
|
Create a string from a C++ char array. |
String(SByte*) , String(SByte*, Int32, Int32) -or- |
|
Create a string from ASCII characters. |
Creating strings
The most commonly used technique for creating strings programmatically is simple assignment, as illustrated in this example. The String class also includes four types of constructor overloads that let you create strings from the following values:
-
From a character array (an array of UTF-16-encoded characters). You can create a new String object from the characters in the entire array or a portion of it. The String(Char[]) constructor copies all the characters in the array to the new string. The String(Char[], Int32, Int32) constructor copies the characters from index startIndex to index startIndex + length – 1 to the new string. If length is zero, the value of the new string is String.Empty.
If your code repeatedly instantiates strings that have the same value, you can improve application performance by using an alternate means of creating strings. For more information, see Handling repetitive strings.
-
From a single character that is duplicated zero, one, or more times, by using the String(Char, Int32) constructor. If count is zero, the value of the new string is String.Empty.
-
From a pointer to a null-terminated character array, by using the String(Char*) or String(Char*, Int32, Int32) constructor. Either the entire array or a specified range can be used to initialize the string. The constructor copies a sequence of Unicode characters starting from the specified pointer or from the specified pointer plus startIndex and continuing to the end of the array or for length characters. If value is a null pointer or length is zero, the constructor creates a string whose value is String.Empty. If the copy operation proceeds to the end of the array and the array is not null-terminated, the constructor behavior is system-dependent. Such a condition might cause an access violation.
The array must contain Unicode characters. In C++, this means that the character array must be defined either as the managed Char[] type or the unmanaged wchar_t[] type.
If the String(Char*) overload is called and the array is not null-terminated, or if the String(Char*, Int32, Int32) overload is called and startIndex + length -1 includes a range that it outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur. In addition, on the Intel Itanium processor, calls to the String(Char*, Int32, Int32) constructor may throw a DataMisalignedException exception. If this occurs, call the String(Char[], Int32, Int32) instead.
-
From a pointer to a signed byte array. Either the entire array or a specified range can be used to initialize the string. The sequence of bytes can be interpreted by using the default code page encoding, or an encoding can be specified in the constructor call. If the constructor tries to instantiate a string from an entire array that is not null-terminated, or if the range of the array from value + startIndex to value + startIndex + length -1 is outside of the memory allocated for the array, the behavior of this constructor is system-dependent, and an access violation may occur.
The three constructors that include a signed byte array as a parameter are designed primarily to convert a C++ char array to a string, as shown in this example:
using namespace System; void main() { char chars[] = { 'a', 'b', 'c', 'd', '\x00' }; char* charPtr = chars; String^ value = gcnew String(charPtr); Console::WriteLine(value); } // The example displays the following output: // abcd
Because the String(SByte*) and String(SByte*, Int32, Int32) constructors interpret value by using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems.
Handling repetitive strings
Apps that parse or decode streams of text often use the String(Char[], Int32, Int32) constructor or the StringBuilder.Append(Char[], Int32, Int32) method to convert sequences of characters into a string. Repeatedly creating new strings with the same value instead of creating and reusing one string wastes memory. If you are likely to create the same string value repeatedly by calling the String(Char[], Int32, Int32) constructor, even if you do not know in advance what those identical string values may be, you can use a lookup table instead.
For example, suppose you read and parse a stream of characters from a file that contains XML tags and attributes. When you parse the stream, you repeatedly encounter certain tokens (that is, sequences of characters that have a symbolic meaning). Tokens equivalent to the strings "0", "1", "true", and "false" are likely to occur frequently in an XML stream.
Instead of converting each token into a new string, you can create a System.Xml.NameTable object to hold commonly occurring strings. The NameTable object improves performance, because it retrieves stored strings without allocating temporary memory. When you encounter a token, use the NameTable.Get(Char[], Int32, Int32) method to retrieve the token from the table. If the token exists, the method returns the corresponding string. If the token does not exist, use the NameTable.Add(Char[], Int32, Int32) method to insert the token into the table and to get the corresponding string.
Example 1: Using string assignment
The following example creates a new string by assigning it a string literal. It creates a second string by assigning the value of the first string to it. These are the two most common ways to instantiate a new String object.
Example 2: Using a character array
The following example demonstrates how to create a new String object from a character array.
// Unicode Mathematical operators char [] charArr1 = {'\u2200','\u2202','\u200F','\u2205'}; String szMathSymbols = new String(charArr1); // Unicode Letterlike Symbols char [] charArr2 = {'\u2111','\u2118','\u2122','\u2126'}; String szLetterLike = new String (charArr2); // Compare Strings - the result is false Console.WriteLine("The Strings are equal? " + (String.Compare(szMathSymbols, szLetterLike)==0?"true":"false") );
Example 3: Using a portion of a character array and repeating a single character
The following example demonstrates how to create a new String object from a portion of a character array, and how to create a new String object that contains multiple occurrences of a single character.
// Create a Unicode String with 5 Greek Alpha characters String szGreekAlpha = new String('\u0391',5); // Create a Unicode String with a Greek Omega character String szGreekOmega = new String(new char [] {'\u03A9','\u03A9','\u03A9'},2,1); String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone()); // Examine the result Console.WriteLine(szGreekLetters); // The first index of Alpha int ialpha = szGreekLetters.IndexOf('\u0391'); // The last index of Omega int iomega = szGreekLetters.LastIndexOf('\u03A9'); Console.WriteLine("The Greek letter Alpha first appears at index " + ialpha + " and Omega last appears at index " + iomega + " in this String.");
Example 4: Using a pointer to a character array
The following example demonstrates how to create a new String object from a pointer to an array of characters. The C# example must be compiled by using the /unsafe compiler switch.
using System; public class Example { public static unsafe void Main() { char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\u0000' }; string value; fixed (char* charPtr = characters) { value = new String(charPtr); } Console.WriteLine(value); } } // The example displays the following output: // Hello world!
Example 5: Instantiating a string from a pointer and a range of an array
The following example examines the elements of a character array for either a period or an exclamation point. If one is found, it instantiates a string from the characters in the array that precede the punctuation symbol. If not, it instantiates a string with the entire contents of the array. The C# example must be compiled using the /unsafe compiler switch.
using System; public class Example { public static unsafe void Main() { char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\u0000' }; String value; fixed (char* charPtr = characters) { int length = 0; Char* iterator = charPtr; while (*iterator != '\x0000') { if (*iterator == '!' || *iterator == '.') break; iterator++; length++; } value = new String(charPtr, 0, length); } Console.WriteLine(value); } } // The example displays the following output: // Hello World
Example 6: Instantiating a string from a pointer to a signed byte array
The following example demonstrates how you can create an instance of the String class with the String(SByte*) constructor.
unsafe { // Null terminated ASCII characters in an sbyte array String szAsciiUpper = null; sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 }; // Instruct the Garbage Collector not to move the memory fixed(sbyte* pAsciiUpper = sbArr1) { szAsciiUpper = new String(pAsciiUpper); } String szAsciiLower = null; sbyte[] sbArr2 = { 0x61, 0x62, 0x63, 0x00 }; // Instruct the Garbage Collector not to move the memory fixed(sbyte* pAsciiLower = sbArr2) { szAsciiLower = new String(pAsciiLower, 0, sbArr2.Length); } // Prints "ABC abc" Console.WriteLine(szAsciiUpper + " " + szAsciiLower); // Compare Strings - the result is true Console.WriteLine("The Strings are equal when capitalized ? " + (String.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper())==0?"true":"false") ); // This is the effective equivalent of another Compare method, which ignores case Console.WriteLine("The Strings are equal when capitalized ? " + (String.Compare(szAsciiUpper, szAsciiLower, true)==0?"true":"false") ); }