String 构造函数
定义
重载
| String(Char*) |
将 String 类的新实例初始化为由指向 Unicode 字符数组的指定指针指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters. |
| String(Char[]) |
将 String 类的新实例初始化为指定字符数组中指示的 Unicode 字符。Initializes a new instance of the String class to the Unicode characters indicated in the specified character array. |
| String(ReadOnlySpan<Char>) |
将 String 类的新实例初始化为指定只读范围中指示的 Unicode 字符。Initializes a new instance of the String class to the Unicode characters indicated in the specified read-only span. |
| String(SByte*) |
将 String 类的新实例初始化为由指向 8 位有符号整数数组的指针指示的值。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) |
将 String 类的新实例初始化为由重复指定次数的指定 Unicode 字符指示的值。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) |
将 String 类的新实例初始化为由指向 Unicode 字符数组的指定指针指示的值、该数组内的起始字符位置和一个长度指示的值。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) |
将 String 类的新实例初始化为由 Unicode 字符数组、该数组内的起始字符位置和一个长度指示的值。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) |
将 String 类的新实例初始化为由指向 8 位有符号整数数组的指定指针、该数组内的起始位置和一个长度指示的值。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) |
将 String 的新实例初始化为由指向 8 位有符号整数数组的指定指针、该数组内的起始位置、长度以及 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
ParametersParameters
不同Exceptions
我要调用哪种方法?Which method do I call?
创建字符串Creating strings
处理重复的字符串Handle repetitive strings
实例化字符串示例:Examples of instantiating strings:
使用字符串赋值Use string assignment
使用字符数组Use a character array
使用字符数组的一部分并重复使用单个字符Use a portion of a character array and repeating a single character
使用指向字符数组的指针Use a pointer to a character array
使用指针和数组的范围Use a pointer and a range of an array
使用带符号字节数组的指针Use a pointer to a signed byte array
重载的构造函数语法Overloaded constructor syntax
字符串构造函数分为两类:不带指针参数的类,以及带有指针参数的构造函数。String constructors fall into two categories: those without pointer parameters, and those with pointer parameters. 使用指针的构造函数不符合 CLS。The constructors that use pointers are not CLS-compliant. 此外,Visual Basic 不支持使用指针,并且 c # 要求使用指针的代码在不安全的上下文中运行。In addition, Visual Basic does not support the use of pointers, and C# requires code that uses pointers to run in an unsafe context. 有关详细信息,请参阅 unsafe。For more information, see unsafe.
有关选择重载的其他指导,请参阅 应该调用哪种方法?。For additional guidance on choosing an overload, see Which method do I call?.
String(Char[] value)
将新实例初始化为由 Unicode 字符数组指示的值。Initializes the new instance to the value indicated by an array of Unicode characters. 此构造函数将 Unicode 字符复制 (示例) 。This constructor copies Unicode characters(example).
String(Char[] value, Int32 startIndex, Int32 length)
将新实例初始化为由 Unicode 字符数组指示的值、该数组内的起始字符位置和长度 (示例) 。Initializes the new instance to the value indicated by an array of Unicode characters, a starting character position within that array, and a length (example).
String(Char c, Int32 count)
将新的实例初始化为指定 Unicode 字符指示的值, (示例) 重复指定的次数。Initializes the new instance to the value indicated by a specified Unicode character repeated a specified number of times (example).
String(char* value)
(不符合 CLS) 将新的实例初始化为由指向 Unicode 字符数组的指针指示的值,该数组由 null 字符 (U + 0000 或 "\ 0" ) 终止。(Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of Unicode characters that is terminated by a null character (U+0000 or '\0'). (示例) 。(example).
权限: SecurityCriticalAttribute 需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.
String(char* value, Int32 startIndex, Int32 length)
(不符合 CLS) 将新的实例初始化为由指向 Unicode 字符数组的指针、该数组内的起始字符位置和一个长度指示的值。(Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of Unicode characters, a starting character position within that array, and a length. 构造函数从 value 索引处开始复制 Unicode 字符 startIndex ,并在索引-1 处结束, startIndex + length (示例) 。The constructor copies the Unicode characters from value starting at index startIndex and ending at index startIndex + length - 1 (example).
权限: SecurityCriticalAttribute 需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.
String(SByte* value)
(不符合 CLS) 将新的实例初始化为由指向8位有符号整数数组的指针指示的值。(Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers. 假定数组表示使用当前系统代码页编码的字符串 (即) 指定的编码 Encoding.Default 。The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by Encoding.Default). 构造函数将处理从 value 指针指定的位置开始的字符,直到到达 (0x00) (示例) 。The constructor processes characters from value starting from the location specified by the pointer until a null character (0x00) is reached (example).
权限: SecurityCriticalAttribute 需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.
String(SByte* value, Int32 startIndex, Int32 length)
(不符合 CLS) 将新实例初始化为由指向8位有符号整数数组的指针、该数组内的起始位置和一个长度指示的值。(Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, and a length. 假定数组表示使用当前系统代码页编码的字符串 (即) 指定的编码 Encoding.Default 。The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by Encoding.Default). 构造函数从开始 startIndex ,到 startIndex + length -1 (示例) 的值处理字符。The constructor processes characters from value starting at startIndex and ending at startIndex + length - 1 (example).
权限: SecurityCriticalAttribute 需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.
String(SByte* value, Int32 startIndex, Int32 length, Encoding enc)
(不符合 CLS) 将新实例初始化为由指向8位有符号整数数组的指针、该数组内的起始位置、长度和对象指示的值 Encoding 。(Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.
权限: SecurityCriticalAttribute 需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.
参数Parameters
下面是 String 不包含指针参数的构造函数所使用的参数的完整列表。Here is a complete list of parameters used by String constructors that don't include a pointer parameter. 对于每个重载使用的参数,请参阅上述重载语法。For the parameters used by each overload, see the overload syntax above.
| 参数Parameter | 类型Type | 说明Description |
|---|---|---|
value |
Char[]Char[] | Unicode 字符的数组。An array of Unicode characters. |
c |
Char | 一个 Unicode 字符。A Unicode character. |
startIndex |
Int32 | value新字符串中第一个字符的起始位置。The starting position in value of the first character in the new string.默认值:0Default value: 0 |
length |
Int32 | 要包含在新字符串中的中的字符数 value 。The number of characters in value to include in the new string.默认值:30Array.LengthDefault value: Array.Length |
count |
Int32 | c在新字符串中重复字符的次数。The number of times the character c is repeated in the new string. 如果 count 为零,则新对象的值为 String.Empty 。If count is zero, the value of the new object is String.Empty. |
下面是 String 包含指针参数的构造函数所使用的参数的完整列表。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* |
指向以 null 结尾的 Unicode 字符数组的指针或一个8位有符号整数数组。A pointer to a null-terminated array of Unicode characters or an array of 8-bit signed integers. 如果 value 为 null 或空数组,则新字符串的值为 String.Empty 。If value is null or an empty array, the value of the new string is String.Empty. |
startIndex |
Int32 | 数组元素的索引,该元素定义新字符串中的第一个字符。The index of the array element that defines the first character in the new string. 默认值:0Default value: 0 |
length |
Int32 | 用于创建新字符串的数组元素的数目。The number of array elements to use to create the new string. 如果 length 为零,则构造函数将创建一个值为的字符串 String.Empty 。If length is zero, the constructor creates a string whose value is String.Empty. 默认值:30Array.LengthDefault value: Array.Length |
enc |
Encoding | 一个对象,该对象指定如何对 value 数组进行编码。An object that specifies how the value array is encoded.默认值: Encoding.Default ,或系统的当前 ANSI 代码页Default value: Encoding.Default, or the system's current ANSI code page |
例外Exceptions
下面是不包含指针参数的构造函数引发的异常列表。Here's a list of exceptions thrown by constructors that don't include pointer parameters.
| 例外Exception | 条件Condition | 引发者Thrown by |
|---|---|---|
| ArgumentNullException | value 为 null。value is null. |
String(Char[], Int32, Int32) |
| ArgumentOutOfRangeException | startIndex、 length 或 count 小于零。startIndex,length, or count is less than zero.或-or- startIndex 与 length 的和大于 value 中的元素数。The sum of startIndex and length is greater than the number of elements in value.或-or- count 小于零。count is less than zero. |
String(Char, Int32) String(Char[], Int32, Int32) |
下面是包含指针参数的构造函数引发的异常列表。Here's a list of exceptions thrown by constructors that include pointer parameters.
| 例外Exception | 条件Condition | 引发者Thrown by |
|---|---|---|
| ArgumentException | value 指定包含无效 Unicode 字符的数组。value specifies an array that contains an invalid Unicode character.或-or- value或 value + startIndex 指定的地址小于64k。value or value + startIndex specifies an address that is less than 64K.或-or- String无法从字节数组初始化新的实例, value 因为不 value 使用默认代码页编码。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. |
| ArgumentNullException | value 为 null。value is null. |
String(SByte*) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32, Encoding) |
| ArgumentOutOfRangeException | 当前进程不具有对所有通过地址访问的字符的读取访问权限。The current process does not have read access to all the addressed characters. 或-or- startIndex 或 length 小于零,value + startIndex 导致指针溢出,或者当前进程不具有对所有寻址字符的读取访问权限。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. |
| AccessViolationException | value,或 value + startIndex + length 为-1,则指定无效的地址。value, or value + startIndex + length - 1, specifies an invalid address. |
String(SByte*) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32, Encoding) |
我要调用哪种方法?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. | String(Char[]) (示例) String(Char[]) (example) |
| 从字符数组的一部分创建字符串。Create a string from a portion of a character array. | String(Char[], Int32, Int32) (示例) String(Char[], Int32, Int32) (example) |
| 创建多次重复相同字符的字符串。Create a string that repeats the same character multiple times. | String(Char, Int32) (示例) String(Char, Int32) (example) |
| 从指向 Unicode 或宽字符数组的指针创建一个字符串。Create a string from a pointer to a Unicode or wide character array. | String(Char*) |
| 使用其指针从 Unicode 或宽字符数组的一部分创建字符串。Create a string from a portion of a Unicode or wide character array by using its pointer. | String(Char*, Int32, Int32) |
创建 c + + 数组中的字符串 char 。Create a string from a C++ char array. |
String(SByte*), String(SByte*, Int32, Int32)String(SByte*), String(SByte*, Int32, Int32) 或-or- String(SByte*, Int32, Int32, Encoding) |
| 从 ASCII 字符创建一个字符串。Create a string from ASCII characters. | ASCIIEncoding.GetString |
创建字符串Create strings
以编程方式创建字符串时最常用的方法是简单赋值,如 本示例中所示。The most commonly used technique for creating strings programmatically is simple assignment, as illustrated in this example. String类还包括四种类型的构造函数重载,可用于从以下值创建字符串:The String class also includes four types of constructor overloads that let you create strings from the following values:
从字符数组 (由 UTF-16 编码的字符组成的数组) 。From a character array (an array of UTF-16-encoded characters). 您可以 String 从整个数组或其中某个部分的字符创建新的对象。You can create a new String object from the characters in the entire array or a portion of it. String(Char[])构造函数将数组中的所有字符复制到新字符串中。The String(Char[]) constructor copies all the characters in the array to the new string. String(Char[], Int32, Int32)构造函数将索引中的字符复制
startIndex到索引startIndex+length-1 到新的字符串。The String(Char[], Int32, Int32) constructor copies the characters from indexstartIndexto indexstartIndex+length- 1 to the new string. 如果length为零,则新字符串的值为 String.Empty 。Iflengthis 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.
使用构造函数从零次、一次或多次重复的单个字符 String(Char, Int32) 。From a single character that is duplicated zero, one, or more times, by using the String(Char, Int32) constructor. 如果
count为零,则新字符串的值为 String.Empty 。Ifcountis zero, the value of the new string is String.Empty.通过使用 String(Char*) 或构造函数从指向以 null 结尾的字符数组的指针 String(Char*, Int32, Int32) 。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. 构造函数从指定的指针或从指定的指针加上
startIndex并继续到数组的末尾或为字符复制一系列 Unicode 字符length。The constructor copies a sequence of Unicode characters starting from the specified pointer or from the specified pointer plusstartIndexand continuing to the end of the array or forlengthcharacters. 如果value为 null 指针或length为零,则构造函数将创建一个值为的字符串 String.Empty 。Ifvalueis a null pointer orlengthis zero, the constructor creates a string whose value is String.Empty. 如果复制操作继续到数组末尾,并且数组不是以 null 终止的,则构造函数行为与系统相关。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.如果数组包含任何嵌入的 null 字符 (U + 0000 或 "\ 0" ) 并且 String(Char*, Int32, Int32) 调用了重载,则字符串实例将包含包含
length任何嵌入的 null 字符。If the array contains any embedded null characters (U+0000 or '\0') and the String(Char*, Int32, Int32) overload is called, the string instance containslengthcharacters including any embedded nulls. 下面的示例演示在将包含两个 null 字符的数组的指针传递到方法时会发生的情况 String(Char*, Int32, Int32) 。The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the String(Char*, Int32, Int32) method. 由于地址是数组的开头,数组中的所有元素都将添加到字符串,因此构造函数将实例化包含10个字符的字符串,包括两个嵌入的 null。Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. 另一方面,如果将同一个数组传递给 String(Char*) 构造函数,则结果是一个四个字符的字符串,该字符串不包含第一个 null 字符。On the other hand, if the same array is passed to the String(Char*) constructor, the result is a four-character string that does not include the first null character.using namespace System; void main() { wchar_t chars[] = { L'a', L'b', L'c', L'd', L'\0', L'A', L'B', L'C', L'D', L'\0' }; Char* chPtr = chars; String^ s = gcnew String(chPtr, 0, sizeof(chars) / sizeof (wchar_t)); for each (Char ch in s) Console::Write("{0:X4} ", Convert::ToUInt16(ch)); Console::WriteLine(); s = gcnew String(chPtr); for each (Char ch in s) Console::Write("{0:X4} ", Convert::ToUInt16(ch)); Console::WriteLine(); } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064using System; public class Example { public unsafe static void Main() { char[] chars = { 'a', 'b', 'c', 'd', '\0', 'A', 'B', 'C', 'D', '\0' }; string s = null; fixed(char* chPtr = chars) { s = new string(chPtr, 0, chars.Length); } foreach (var ch in s) Console.Write("{0:X4} ", Convert.ToUInt16(ch)); Console.WriteLine(); fixed(char* chPtr = chars) { s = new string(chPtr); } foreach (var ch in s) Console.Write("{0:X4} ", Convert.ToUInt16(ch)); Console.WriteLine(); } } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064数组必须包含 Unicode 字符。The array must contain Unicode characters. 在 c + + 中,这意味着必须将字符数组定义为 managed Char [] 类型或非托管
wchar_t[] 类型。In C++, this means that the character array must be defined either as the managed Char[] type or the unmanagedwchar_t[] type.如果 String(Char*) 调用了重载,且数组不是以 null 结尾的,或者如果 String(Char*, Int32, Int32) 调用了重载,并且
startIndex+length-1 包括的范围超出了为字符序列分配的内存,则构造函数的行为将与系统相关,并可能会发生访问冲突。If the String(Char*) overload is called and the array is not null-terminated, or if the String(Char*, Int32, Int32) overload is called andstartIndex+length-1 includes a range that is outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur.从指向有符号字节数组的指针。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. 如果构造函数尝试从整个数组中实例化不是以 null 结尾的字符串,或者从
value+startIndex-1 到-1 的数组范围超出了为value+startIndex+length数组分配的内存,则此构造函数的行为与系统相关,并可能会发生访问冲突。If the constructor tries to instantiate a string from an entire array that is not null-terminated, or if the range of the array fromvalue+startIndextovalue+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.这三个构造函数将有符号字节数组作为参数,主要用于将 c + +
char数组转换为字符串,如以下示例中所示:The three constructors that include a signed byte array as a parameter are designed primarily to convert a C++chararray 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如果数组包含任何 null 字符 ( "\ 0" ) 或值为0的字节 String(SByte*, Int32, Int32) ,并且调用了重载,则字符串实例将包含
length任何嵌入的 null 字符。If the array contains any null characters ('\0') or bytes whose value is 0 and the String(SByte*, Int32, Int32) overload is called, the string instance containslengthcharacters including any embedded nulls. 下面的示例演示在将包含两个 null 字符的数组的指针传递到方法时会发生的情况 String(SByte*, Int32, Int32) 。The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the String(SByte*, Int32, Int32) method. 由于地址是数组的开头,数组中的所有元素都将添加到字符串,因此构造函数将实例化包含10个字符的字符串,包括两个嵌入的 null。Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. 另一方面,如果将同一个数组传递给 String(SByte*) 构造函数,则结果是一个四个字符的字符串,该字符串不包含第一个 null 字符。On the other hand, if the same array is passed to the String(SByte*) constructor, the result is a four-character string that does not include the first null character.using namespace System; void main() { char bytes[] = { 0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42,0x43, 0x44, 0x00 }; char* bytePtr = bytes; String^ s = gcnew String(bytePtr, 0, sizeof(bytes) / sizeof (char)); for each (Char ch in s) Console::Write("{0:X4} ", Convert::ToUInt16(ch)); Console::WriteLine(); s = gcnew String(bytePtr); for each (Char ch in s) Console::Write("{0:X4} ", Convert::ToUInt16(ch)); Console::WriteLine(); } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064using System; public class Example { public unsafe static void Main() { sbyte[] bytes = { 0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42,0x43, 0x44, 0x00 }; string s = null; fixed (sbyte* bytePtr = bytes) { s = new string(bytePtr, 0, bytes.Length); } foreach (var ch in s) Console.Write("{0:X4} ", Convert.ToUInt16(ch)); Console.WriteLine(); fixed(sbyte* bytePtr = bytes) { s = new string(bytePtr); } foreach (var ch in s) Console.Write("{0:X4} ", Convert.ToUInt16(ch)); Console.WriteLine(); } } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064由于 String(SByte*) 和 String(SByte*, Int32, Int32) 构造函数
value使用默认的 ANSI 代码页进行解释,因此,使用相同的字节数组调用这些构造函数可能会在不同系统上创建具有不同值的字符串。Because the String(SByte*) and String(SByte*, Int32, Int32) constructors interpretvalueby using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems.
处理重复的字符串Handle repetitive strings
分析或解码文本流的应用通常使用 String(Char[], Int32, Int32) 构造函数或方法将 StringBuilder.Append(Char[], Int32, Int32) 字符序列转换为字符串。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. 如果您可能会通过调用构造函数反复创建相同的字符串值 String(Char[], Int32, Int32) ,即使您事先事先不知道这些相同的字符串值,也可以改用查找表。If you are likely to create the same string value repeatedly by calling the String(Char[], Int32, Int32) constructor, even if you don't know in advance what those identical string values may be, you can use a lookup table instead.
例如,假设您从包含 XML 标记和特性的文件中读取和分析字符流。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). 与字符串 "0"、"1"、"true" 和 "false" 等效的标记可能经常出现在 XML 流中。Tokens equivalent to the strings "0", "1", "true", and "false" are likely to occur frequently in an XML stream.
你可以创建一个 System.Xml.NameTable 对象来保存通常出现的字符串,而不是将每个标记转换为一个新字符串。Instead of converting each token into a new string, you can create a System.Xml.NameTable object to hold commonly occurring strings. NameTable对象可提高性能,因为它检索存储的字符串,而不分配临时内存。The NameTable object improves performance, because it retrieves stored strings without allocating temporary memory. 如果遇到标记,请使用 NameTable.Get(Char[], Int32, Int32) 方法从表中检索标记。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. 如果该标记不存在,请使用 NameTable.Add(Char[], Int32, Int32) 方法将该标记插入到表中,并获取相应的字符串。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.
示例1:使用字符串赋值Example 1: Use 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. 这是实例化新对象的两种最常用的方法 String 。These are the two most common ways to instantiate a new String object.
using namespace System;
void main()
{
String^ value1 = L"This is a string.";
String^ value2 = value1;
Console::WriteLine(value1);
Console::WriteLine(value2);
}
// The example displays the following output:
// This is a string.
// This is a string.
using System;
public class Example
{
public static void Main()
{
String value1 = "This is a string.";
String value2 = value1;
Console.WriteLine(value1);
Console.WriteLine(value2);
}
}
// The example displays the following output:
// This is a string.
// This is a string.
Module Example
Public Sub Main()
Dim value1 As String = "This is a string."
Dim value2 As String = value1
Console.WriteLine(value1)
Console.WriteLine(value2)
End Sub
End Module
' The example displays the following output:
' This is a string.
' This is a string.
示例2:使用字符数组Example 2: Use a character array
下面的示例演示如何 String 从字符数组创建新的对象。The following example demonstrates how to create a new String object from a character array.
// Unicode Mathematical operators
wchar_t charArray1[4] = {L'\x2200',L'\x2202',L'\x200F',L'\x2205'};
wchar_t * lptstr1 = &charArray1[ 0 ];
String^ wszMathSymbols = gcnew String( lptstr1 );
// Unicode Letterlike Symbols
wchar_t charArray2[4] = {L'\x2111',L'\x2118',L'\x2122',L'\x2126'};
wchar_t * lptstr2 = &charArray2[ 0 ];
String^ wszLetterLike = gcnew String( lptstr2 );
// Compare Strings - the result is false
Console::WriteLine( String::Concat( L"The Strings are equal? ", (0 == String::Compare( wszLetterLike, wszMathSymbols ) ? (String^)"TRUE" : "FALSE") ) );
// 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") );
' Unicode Mathematical operators
Dim charArr1() As Char = {ChrW(&H2200), ChrW(&H2202), _
ChrW(&H200F), ChrW(&H2205)}
Dim szMathSymbols As New String(charArr1)
' Unicode Letterlike Symbols
Dim charArr2() As Char = {ChrW(&H2111), ChrW(&H2118), _
ChrW(&H2122), ChrW(&H2126)}
Dim szLetterLike As New String(charArr2)
' Compare Strings - the result is false
Console.WriteLine("The strings are equal? " & _
CStr(szMathSymbols.Equals(szLetterLike)))
示例3:使用字符数组的一部分并重复单个字符Example 3: Use a portion of a character array and repeating a single character
下面的示例演示如何 String 从字符数组的一部分创建一个新的对象,以及如何创建一个新的 String 对象,该对象包含单个字符的多个匹配项。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 = gcnew String( L'\x0391',5 );
// Create a Unicode String with a Greek Omega character
wchar_t charArray5[3] = {L'\x03A9',L'\x03A9',L'\x03A9'};
String^ szGreekOmega = gcnew String( charArray5,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( L'\x0391' );
// The last index of Omega
int iomega = szGreekLetters->LastIndexOf( L'\x03A9' );
Console::WriteLine( String::Concat( "The Greek letter Alpha first appears at index ", Convert::ToString( ialpha ) ) );
Console::WriteLine( String::Concat( " and Omega last appears at index ", Convert::ToString( iomega ), " in this String." ) );
// 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.");
' Create a Unicode String with 5 Greek Alpha characters
Dim szGreekAlpha As New String(ChrW(&H0391), 5)
' Create a Unicode String with a Greek Omega character
Dim szGreekOmega As New String(New Char() {ChrW(&H03A9), ChrW(&H03A9), _
ChrW(&H03A9)}, 2, 1)
Dim szGreekLetters As String = String.Concat(szGreekOmega, szGreekAlpha, _
szGreekOmega.Clone())
' Examine the result
Console.WriteLine(szGreekLetters)
' The first index of Alpha
Dim iAlpha As Integer = szGreekLetters.IndexOf(ChrW(&H0391))
' The last index of Omega
Dim iomega As Integer = szGreekLetters.LastIndexOf(ChrW(&H03A9))
Console.WriteLine("The Greek letter Alpha first appears at index {0}.", _
ialpha)
Console.WriteLIne("The Greek letter Omega last appears at index {0}.", _
iomega)
示例4:使用指向字符数组的指针Example 4: Use a pointer to a character array
下面的示例演示如何 String 从指向字符数组的指针创建新的对象。The following example demonstrates how to create a new String object from a pointer to an array of characters. 必须使用编译器开关编译 c # 示例 /unsafe 。The C# example must be compiled by using the /unsafe compiler switch.
using namespace System;
void main()
{
wchar_t characters[] = {L'H',L'e',L'l',L'l',L'o',L' ',
L'W',L'o',L'r',L'l',L'd',L'!',L'\x0000'};
Char* charPtr = characters;
String^ value = gcnew String(charPtr);
Console::WriteLine(value);
}
// The example displays the following output:
// Hello world!
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!
示例5:从指针和数组的范围实例化字符串Example 5: Instantiate 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. 必须使用编译器开关编译 c # 示例 /unsafe 。The C# example must be compiled using the /unsafe compiler switch.
using namespace System;
void main()
{
wchar_t characters[] = {L'H',L'e',L'l',L'l',L'o',L' ',
L'W',L'o',L'r',L'l',L'd',L'!',L'\x0000'};
Char* charPtr = characters;
int length = 0;
Char* iterator = charPtr;
while (*iterator != '\x0000')
{
if (*iterator == L'!' || *iterator == L'.')
break;
*iterator++;
length++;
}
String^ value = gcnew String(charPtr, 0, length);
Console::WriteLine(value);
}
// The example displays the following output:
// Hello World
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
示例6:从指向有符号字节数组的指针实例化字符串Example 6: Instantiate a string from a pointer to a signed byte array
下面的示例演示如何 String 使用构造函数创建类的实例 String(SByte*) 。The following example demonstrates how you can create an instance of the String class with the String(SByte*) constructor.
// Null terminated ASCII characters in a simple char array
char charArray3[4] = {0x41,0x42,0x43,0x00};
char * pstr3 = &charArray3[ 0 ];
String^ szAsciiUpper = gcnew String( pstr3 );
char charArray4[4] = {0x61,0x62,0x63,0x00};
char * pstr4 = &charArray4[ 0 ];
String^ szAsciiLower = gcnew String( pstr4,0,sizeof(charArray4) );
// Prints "ABC abc"
Console::WriteLine( String::Concat( szAsciiUpper, " ", szAsciiLower ) );
// Compare Strings - the result is true
Console::WriteLine( String::Concat( "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper->ToUpper(), szAsciiLower->ToUpper() ) ? (String^)"TRUE" : "FALSE") ) );
// This is the effective equivalent of another Compare method, which ignores case
Console::WriteLine( String::Concat( "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper, szAsciiLower, true ) ? (String^)"TRUE" : "FALSE") ) );
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") );
}
String(Char*)
重要
此 API 不符合 CLS。
public:
String(char* value);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (char* value);
[System.CLSCompliant(false)]
public String (char* value);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<char> -> string
[<System.CLSCompliant(false)>]
new string : nativeptr<char> -> string
参数
- value
- Char*
指向以 null 终止的 Unicode 字符数组的指针。A pointer to a null-terminated array of Unicode characters.
- 属性
例外
当前进程不具有对所有通过地址访问的字符的读取访问权限。The current process does not have read access to all the addressed characters.
value 指定的数组包含无效的 Unicode 字符,或 value 指定的地址小于 64000。value specifies an array that contains an invalid Unicode character, or value specifies an address less than 64000.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(Char[])
public:
String(cli::array <char> ^ value);
public String (char[] value);
public String (char[]? value);
new string : char[] -> string
Public Sub New (value As Char())
参数
- value
- Char[]
Unicode 字符的数组。An array of Unicode characters.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(ReadOnlySpan<Char>)
public:
String(ReadOnlySpan<char> value);
public String (ReadOnlySpan<char> value);
new string : ReadOnlySpan<char> -> string
Public Sub New (value As ReadOnlySpan(Of Char))
参数
- value
- ReadOnlySpan<Char>
Unicode 字符的只读范围。A read-only span of Unicode characters.
适用于
String(SByte*)
重要
此 API 不符合 CLS。
public:
String(System::SByte* value);
[System.CLSCompliant(false)]
public String (sbyte* value);
public String (sbyte* value);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value);
[<System.CLSCompliant(false)>]
new string : nativeptr<sbyte> -> string
new string : nativeptr<sbyte> -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<sbyte> -> string
参数
- value
- SByte*
一个指针,指向以 null 结尾的 8 位带符号整数数组。A pointer to a null-terminated array of 8-bit signed integers. 使用当前系统代码页编码(即由 Default 指定的编码)来解释整数。The integers are interpreted using the current system code page encoding (that is, the encoding specified by Default).
- 属性
例外
value 为 null。value is null.
如果 value 采用 ANSI 进行编码,那么无法使用 value 初始化 String 的新实例。A new instance of String could not be initialized using value, assuming value is encoded in ANSI.
要初始化的新字符串的长度(该长度由 value 的 null 终止字符确定)太大,无法分配。The length of the new string to initialize, which is determined by the null termination character of value, is too large to allocate.
value 指定的地址无效。value specifies an invalid address.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(Char, Int32)
public:
String(char c, int count);
public String (char c, int count);
new string : char * int -> string
Public Sub New (c As Char, count As Integer)
参数
- c
- Char
一个 Unicode 字符。A Unicode character.
- count
- Int32
c 出现的次数。The number of times c occurs.
例外
count 小于零。count is less than zero.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(Char*, Int32, Int32)
重要
此 API 不符合 CLS。
public:
String(char* value, int startIndex, int length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (char* value, int startIndex, int length);
[System.CLSCompliant(false)]
public String (char* value, int startIndex, int length);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<char> * int * int -> string
[<System.CLSCompliant(false)>]
new string : nativeptr<char> * int * int -> string
参数
- value
- Char*
指向 Unicode 字符数组的指针。A pointer to an array of Unicode characters.
- startIndex
- Int32
value 内的起始位置。The starting position within value.
- length
- Int32
要使用的 value 内的字符数。The number of characters within value to use.
- 属性
例外
startIndex 或 length 小于零,value + startIndex 导致指针溢出,或者当前进程不具有对所有寻址字符的读取访问权限。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.
value 指定的数组包含无效的 Unicode 字符,或 value + startIndex 指定的地址小于 64000。value specifies an array that contains an invalid Unicode character, or value + startIndex specifies an address less than 64000.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(Char[], Int32, Int32)
public:
String(cli::array <char> ^ value, int startIndex, int length);
public String (char[] value, int startIndex, int length);
new string : char[] * int * int -> string
Public Sub New (value As Char(), startIndex As Integer, length As Integer)
参数
- value
- Char[]
Unicode 字符的数组。An array of Unicode characters.
- startIndex
- Int32
value 内的起始位置。The starting position within value.
- length
- Int32
要使用的 value 内的字符数。The number of characters within value to use.
例外
value 为 null。value is null.
startIndex 或 length 小于零。startIndex or length is less than zero.
或-or-
startIndex 与 length 的和大于 value 中的元素数。The sum of startIndex and length is greater than the number of elements in value.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(SByte*, Int32, Int32)
重要
此 API 不符合 CLS。
public:
String(System::SByte* value, int startIndex, int length);
[System.CLSCompliant(false)]
public String (sbyte* value, int startIndex, int length);
public String (sbyte* value, int startIndex, int length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value, int startIndex, int length);
[<System.CLSCompliant(false)>]
new string : nativeptr<sbyte> * int * int -> string
new string : nativeptr<sbyte> * int * int -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<sbyte> * int * int -> string
参数
- value
- SByte*
指向 8 位带符号整数数组的指针。A pointer to an array of 8-bit signed integers. 使用当前系统代码页编码(即由 Default 指定的编码)来解释整数。The integers are interpreted using the current system code page encoding (that is, the encoding specified by Default).
- startIndex
- Int32
value 内的起始位置。The starting position within value.
- length
- Int32
要使用的 value 内的字符数。The number of characters within value to use.
- 属性
例外
value 为 null。value is null.
startIndex 或 length 小于零。startIndex or length is less than zero.
或-or-
由 value + startIndex 指定的地址对于当前平台而言太大;也就是说,此地址计算溢出。The address specified by value + startIndex is too large for the current platform; that is, the address calculation overflowed.
或-or-
要初始化的新字符串的长度太大,无法分配。The length of the new string to initialize is too large to allocate.
由 value + startIndex 指定的地址小于 64K。The address specified by value + startIndex is less than 64K.
或-or-
如果 value 采用 ANSI 进行编码,那么无法使用 value 初始化 String 的新实例。A new instance of String could not be initialized using value, assuming value is encoded in ANSI.
value、startIndex 和 length 共同指定的地址无效。value, startIndex, and length collectively specify an invalid address.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.
适用于
String(SByte*, Int32, Int32, Encoding)
重要
此 API 不符合 CLS。
public:
String(System::SByte* value, int startIndex, int length, System::Text::Encoding ^ enc);
[System.CLSCompliant(false)]
public String (sbyte* value, int startIndex, int length, System.Text.Encoding enc);
public String (sbyte* value, int startIndex, int length, System.Text.Encoding enc);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value, int startIndex, int length, System.Text.Encoding enc);
[<System.CLSCompliant(false)>]
new string : nativeptr<sbyte> * int * int * System.Text.Encoding -> string
new string : nativeptr<sbyte> * int * int * System.Text.Encoding -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<sbyte> * int * int * System.Text.Encoding -> string
参数
- value
- SByte*
指向 8 位带符号整数数组的指针。A pointer to an array of 8-bit signed integers.
- startIndex
- Int32
value 内的起始位置。The starting position within value.
- length
- Int32
要使用的 value 内的字符数。The number of characters within value to use.
- enc
- Encoding
一个对象,用于指定如何对 value 所引用的数组进行编码。An object that specifies how the array referenced by value is encoded. 如果 enc 为 null,则假定以 ANSI 编码。If enc is null, ANSI encoding is assumed.
- 属性
例外
value 为 null。value is null.
startIndex 或 length 小于零。startIndex or length is less than zero.
或-or-
由 value + startIndex 指定的地址对于当前平台而言太大;也就是说,此地址计算溢出。The address specified by value + startIndex is too large for the current platform; that is, the address calculation overflowed.
或-or-
要初始化的新字符串的长度太大,无法分配。The length of the new string to initialize is too large to allocate.
由 value + startIndex 指定的地址小于 64K。The address specified by value + startIndex is less than 64K.
或-or-
如果 value 按照指定的 enc 进行编码,那么无法使用 value 初始化 String 的新实例。A new instance of String could not be initialized using value, assuming value is encoded as specified by enc.
value、startIndex 和 length 共同指定的地址无效。value, startIndex, and length collectively specify an invalid address.
注解
备注
有关此和其他构造函数重载的示例和综合使用信息 String ,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.