String 建構函式
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
初始化 String 類別的新執行個體。
多載
String(Char*) |
將 String 類別的新執行個體初始化為 Unicode 字元陣列的指定指標所指示的值。 |
String(Char[]) |
將 String 類別新執行個體初始化為所指定字元陣列中指出的 Unicode 字元。 |
String(ReadOnlySpan<Char>) |
將 String 類別新執行個體初始化為所指定唯讀範圍中指出的 Unicode 字元。 |
String(SByte*) |
將 String 類別的新執行個體初始化為 8 位元帶正負號整數 (Signed Integer) 陣列的指標所指示的值。 |
String(Char, Int32) |
將 String 類別的新執行個體初始化為由重複指定次數的指定 Unicode 字元所指示的值。 |
String(Char*, Int32, Int32) |
將 String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置以及長度等等的指定指標所指示的值。 |
String(Char[], Int32, Int32) |
將 String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置和長度等等所指示的值。 |
String(SByte*, Int32, Int32) |
將 String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置和長度的指定指標所指示的值。 |
String(SByte*, Int32, Int32, Encoding) |
將 String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置、長度和 Encoding 物件的指定指標所指示的值。 |
備註
本節內容:
多載建構函式語法
參數
例外狀況
我呼叫哪一種方法?
建立字串
處理重複字串
具現化字串的範例:
使用字串指派
使用字元陣列
使用字元陣列的一部分並重複單一字元
使用字元陣列的指標
使用指標和陣列的範圍
使用帶正負號位元組陣列的指標
多載建構函式語法
字串建構函式分為兩個類別:沒有指標參數的建構函式,以及具有指標參數的類別。 使用指標的建構函式不符合 CLS 規範。 此外,Visual Basic 不支援使用指標,而 C# 則需要使用指標在不安全的內容中執行的程式碼。 如需詳細資訊,請參閱 unsafe。
如需選擇多載的其他指引,請參閱 我呼叫哪一種方法?。
String(Char[] value)
將新實例初始化為 Unicode 字元陣列所表示的值。 這個建構函式會複製 Unicode 字元 (範例) 。
String(Char[] value, Int32 startIndex, Int32 length)
將新的實例初始化為 Unicode 字元陣列、該陣列內的起始字元位置,以及 (範例) 所指示的值。
String(Char c, Int32 count)
將新的實例初始化為指定的 Unicode 字元所指示的值, (範例) 重複指定的次數。
String(char* value)
(不符合 CLS 標準的) 將新實例初始化為由 Unicode 字元陣列指標所表示的值,該陣列由 null 字元終止, (U+0000 或 '\0') 。 (範例) 。
許可權: SecurityCriticalAttribute 需要立即呼叫端的完整信任。 部分信任或透明程式碼無法使用這個成員。
String(char* value, Int32 startIndex, Int32 length)
(不符合 CLS 標準的) 將新實例初始化為 Unicode 字元陣列的指標、該陣列內的起始字元位置,以及長度所表示的值。 建構函式會複製 Unicode 字元,從 value
索引開始並結束于 index startIndex
length
startIndex
+ - 1 (範例) 。
許可權: SecurityCriticalAttribute 需要立即呼叫端的完整信任。 部分信任或透明程式碼無法使用這個成員。
String(SByte* value)
(不符合 CLS 標準的) 將新實例初始化為 8 位帶正負號整數陣列指標所表示的值。 陣列假設表示使用目前系統字碼頁編碼的字串, (也就是) 所 Encoding.Default 指定的編碼方式。 建構函式會從指標指定的位置開始處理字元 value
,直到到達 null 字元 (0x00) (範例) 為止。
許可權: SecurityCriticalAttribute 需要立即呼叫端的完整信任。 部分信任或透明程式碼無法使用這個成員。
String(SByte* value, Int32 startIndex, Int32 length)
(不符合 CLS 標準的) 將新實例初始化為 8 位帶正負號整數陣列的指標、該陣列內的起始位置,以及長度所表示的值。 陣列假設表示使用目前系統字碼頁編碼的字串, (也就是) 所 Encoding.Default 指定的編碼方式。 建構函式會處理從 值開始 startIndex
和結尾的 startIndex
+ length
字元 - 1 (範例) 。
許可權: SecurityCriticalAttribute 需要立即呼叫端的完整信任。 部分信任或透明程式碼無法使用這個成員。
String(SByte* value, Int32 startIndex, Int32 length, Encoding enc)
(不符合 CLS 標準的) 將新實例初始化為 8 位帶正負號整數陣列的指標、該陣列內的起始位置、長度和 Encoding 物件所表示的值。
許可權: SecurityCriticalAttribute 需要立即呼叫端的完整信任。 部分信任或透明程式碼無法使用這個成員。
參數
以下是不包含指標參數之建構函式所使用的 String 參數完整清單。 如需每個多載所使用的參數,請參閱上述多載語法。
參數 | 類型 | 描述 |
---|---|---|
value |
Char[] | Unicode 字元陣列。 |
c |
Char | Unicode 字元。 |
startIndex |
Int32 | 新字串中第一個字元的起始位置 value 。預設值:0 |
length |
Int32 | 要 value 包含在新字串中的字元數。預設值:Array.Length |
count |
Int32 | 字元 c 在新字串中重複的次數。 如果 count 為零,則新物件的 String.Empty 值為 。 |
以下是包含指標參數之建構函式所使用的 String 參數完整清單。 如需每個多載所使用的參數,請參閱上述多載語法。
參數 | 類型 | 描述 |
---|---|---|
value |
Char* -或- SByte* |
Unicode 字元的 Null 終止陣列或 8 位帶正負號整數的陣列指標。 如果 value 為 null 或空陣列,則新字串的值為 String.Empty 。 |
startIndex |
Int32 | 定義新字串中第一個字元之陣列專案的索引。 預設值:0 |
length |
Int32 | 要用來建立新字串的陣列元素數目。 如果 length 為零,建構函式會建立值為 String.Empty 的字串。 預設值:Array.Length |
enc |
Encoding | 物件,指定陣列的編碼方式 value 。預設值: Encoding.Default 、 或系統的目前 ANSI 字碼頁 |
例外狀況
以下是不包含指標參數的建構函式擲回的例外狀況清單。
例外狀況 | 條件 | 擲回者 |
---|---|---|
ArgumentNullException | value 為 null 。 |
String(Char[], Int32, Int32) |
ArgumentOutOfRangeException | startIndex 、 length 或 count 小於零。-或- startIndex 和 length 的總和大於 value 中的項目數。-或- count 小於零。 |
String(Char, Int32) String(Char[], Int32, Int32) |
以下是包含指標參數的建構函式擲回的例外狀況清單。
例外狀況 | 條件 | 擲回者 |
---|---|---|
ArgumentException | value 指定包含無效 Unicode 字元的陣列。-或- value 或 value + startIndex 指定小於 64K 的位址。-或- 無法從 value 位元組陣列初始化新的 String 實例,因為 value 不會使用預設字碼頁編碼。 |
具有指標的所有建構函式。 |
ArgumentNullException | value 為 null。 |
String(SByte*) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32, Encoding) |
ArgumentOutOfRangeException | 目前的處理序沒有讀取所有定址字元的權限。 -或- startIndex 或 length 小於零、value + startIndex 導致指標溢位,或目前的處理序沒有所有定址字元的讀取權限。-或- 新字串的長度太大而無法配置。 |
具有指標的所有建構函式。 |
AccessViolationException | value 或 value + + startIndex length - 1,指定不正確位址。 |
String(SByte*) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32, Encoding) |
我呼叫哪一種方法?
收件者 | 呼叫或使用 |
---|---|
建立字串。 | 從字串常值或現有字串指派, (範例) |
從整個字元陣列建立字串。 | String(Char[]) (範例) |
從字元陣列的一部分建立字串。 | String(Char[], Int32, Int32) (範例) |
建立重複相同字元多次的字串。 | String(Char, Int32) (範例) |
從 Unicode 或寬字元陣列的指標建立字串。 | String(Char*) |
使用其指標,從 Unicode 或寬字元陣列的一部分建立字串。 | String(Char*, Int32, Int32) |
從 C++ char 陣列建立字串。 |
String(SByte*), String(SByte*, Int32, Int32) -或- String(SByte*, Int32, Int32, Encoding) |
從 ASCII 字元建立字串。 | ASCIIEncoding.GetString |
建立字串
以程式設計方式建立字串最常使用的技巧是簡單的指派,如 本範例所示。 類別 String 也包含四種類型的建構函式多載,可讓您從下列值建立字串:
從字元陣列 (UTF-16 編碼字元陣列) 。 您可以從整個陣列或其中一部分的字元建立新的 String 物件。 建 String(Char[]) 構函式會將陣列中的所有字元複製到新的字串。 建構函式 String(Char[], Int32, Int32) 會將字元從索引複製到 index
startIndex
startIndex
+length
- 1 複製到新的字串。 如果length
為零,則新字串的值為 String.Empty 。如果您的程式碼重複具現化具有相同值的字串,您可以使用建立字串的替代方式來改善應用程式效能。 如需詳細資訊,請參閱 處理重複的字串。
使用 建構函式,從重複零、一次或多次 String(Char, Int32) 的單一字元。 如果
count
為零,則新字串的值為 String.Empty 。使用 String(Char*) 或 String(Char*, Int32, Int32) 建構函式,從以 Null 結尾的字元陣列指標。 整個陣列或指定的範圍都可以用來初始化字串。 建構函式會複製一連串的 Unicode 字元,從指定的指標或從指定的指標加上
startIndex
,然後繼續到陣列結尾或字元length
。 如果value
為 Null 指標或length
為零,建構函式會建立值為 String.Empty 的字串。 如果複製作業繼續到陣列結尾,且陣列不是以 Null 終止,則建構函式行為是系統相依的。 這類狀況可能會導致存取違規。如果陣列包含任何內嵌 Null 字元, (U+0000 或 '\0') 且 String(Char*, Int32, Int32) 呼叫多載,則字串實例會
length
包含包含任何內嵌 Null 的字元。 下列範例顯示當包含兩個 Null 字元的陣列指標傳遞給 String(Char*, Int32, Int32) 方法時,會發生什麼事。 因為位址是陣列的開頭,而且陣列中的所有元素都會加入字串中,所以建構函式會具現化具有十個字元的字串,包括兩個內嵌的 Null。 另一方面,如果相同的陣列傳遞至 String(Char*) 建構函式,結果就是不包含第一個 Null 字元的四個字元字串。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 0064
using 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($"{(ushort)ch:X4} "); Console.WriteLine(); fixed(char* chPtr = chars) { s = new string(chPtr); } foreach (var ch in s) Console.Write($"{(ushort)ch:X4} "); Console.WriteLine(); } } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064
#nowarn "9" open System let chars = [| 'a'; 'b'; 'c'; 'd'; '\000'; 'A'; 'B'; 'C'; 'D'; '\000' |] let s = use chPtr = fixed chars String(chPtr, 0, chars.Length) for ch in s do printf $"{uint16 ch:X4} " printfn "" let s2 = use chPtr = fixed chars String chPtr for ch in s2 do printf $"{uint16 ch:X4} " printfn "" // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064
陣列必須包含 Unicode 字元。 在 C++ 中,這表示字元陣列必須定義為 Managed Char [] 類型或 Unmanaged
wchar_t
[] 類型。String(Char*)如果呼叫多載且陣列不是以 Null 終止,或呼叫 String(Char*, Int32, Int32) 多載且
startIndex
+length
-1 包含配置給字元序列記憶體以外的範圍,則建構函式的行為與系統相依,而且可能會發生存取違規。從帶正負號位元組陣列的指標。 整個陣列或指定的範圍都可以用來初始化字串。 您可以使用預設字碼頁編碼來解譯位元組序列,也可以在建構函式呼叫中指定編碼。 如果建構函式嘗試從不是以 Null 終止的整個陣列具現化字串,或如果陣列的範圍超出
value
startIndex
startIndex
length
+value
+ + 配置給陣列的記憶體之外,則此建構函式的行為會相依,而且可能會發生存取違規。包含帶正負號位元組陣列做為參數的三個建構函式主要是設計成將 C++
char
陣列轉換成字串,如下列範例所示: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') 或呼叫 String(SByte*, Int32, Int32) 多載的位元組,則字串實例包含
length
包含任何內嵌 Null 的字元。 下列範例顯示當包含兩個 Null 字元的陣列指標傳遞給 String(SByte*, Int32, Int32) 方法時,會發生什麼事。 因為位址是陣列的開頭,而且陣列中的所有元素都會加入字串中,所以建構函式會具現化具有十個字元的字串,包括兩個內嵌的 Null。 另一方面,如果相同的陣列傳遞至 String(SByte*) 建構函式,結果就是不包含第一個 Null 字元的四個字元字串。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 0064
using 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($"{(ushort)ch:X4} "); Console.WriteLine(); fixed(sbyte* bytePtr = bytes) { s = new string(bytePtr); } foreach (var ch in s) Console.Write($"{(ushort)ch:X4} "); Console.WriteLine(); } } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 // 0061 0062 0063 0064
#nowarn "9" open System let bytes = [| 0x61y; 0x62y; 0x063y; 0x064y; 0x00y; 0x41y; 0x42y; 0x43y; 0x44y; 0x00y |] let s = use bytePtr = fixed bytes String(bytePtr, 0, bytes.Length) for ch in s do printf $"{uint16 ch:X4} " printfn "" let s2 = use bytePtr = fixed bytes String bytePtr for ch in s do printf $"{uint16 ch:X4} " printfn "" // 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) 建構函式會使用預設 ANSI 字碼頁來解譯
value
,因此使用相同位元組陣列呼叫這些建構函式可能會建立在不同系統上具有不同值的字串。
處理重複字串
剖析或解碼文字資料流程的應用程式通常會使用建 String(Char[], Int32, Int32) 構函式或 StringBuilder.Append(Char[], Int32, Int32) 方法,將字元序列轉換成字串。 重複建立具有相同值的新字串,而不是建立並重複使用一個字串會浪費記憶體。 如果您可能藉由呼叫 String(Char[], Int32, Int32) 建構函式重複建立相同的字串值,即使您事先不知道這些相同的字串值可能是什麼,您也可以改用查閱表格。
例如,假設您從包含 XML 標記和屬性的檔案讀取和剖析字元資料流。 剖析資料流程時,您會重複遇到某些標記,也就是具有符號意義) 的字元序列 (。 與字串 「0」、「1」、「true」 和 「false」 相等的權杖可能會經常發生在 XML 資料流程中。
您可以建立 System.Xml.NameTable 物件來保存經常發生的字串,而不是將每個權杖轉換成新的字串。 物件 NameTable 可改善效能,因為它會擷取儲存的字串,而不會配置暫存記憶體。 當您遇到權杖時,請使用 NameTable.Get(Char[], Int32, Int32) 方法從資料表擷取權杖。 如果權杖存在,方法會傳回對應的字串。 如果權杖不存在,請使用 NameTable.Add(Char[], Int32, Int32) 方法將權杖插入資料表,並取得對應的字串。
範例 1:使用字串指派
下列範例會藉由指派字串常值來建立新的字串。 它會藉由將第一個字串的值指派給它來建立第二個字串。 這些是具現化新 String 物件最常見的兩種方式。
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.
let value1 = "This is a string."
let value2 = value1
printfn "%s" value1
printfn "%s" 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:使用字元陣列
下列範例示範如何從字元陣列建立新的 String 物件。
// 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
let charArr1 = [| '\u2200'; '\u2202'; '\u200F'; '\u2205' |]
let szMathSymbols = String charArr1
// Unicode Letterlike Symbols
let charArr2 = [| '\u2111'; '\u2118'; '\u2122'; '\u2126' |]
let szLetterLike = String charArr2
// Compare Strings - the result is false
printfn $"The Strings are equal? %b{String.Compare(szMathSymbols, szLetterLike) = 0}"
' 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:使用字元陣列的一部分並重複單一字元
下列範例示範如何從字元陣列的一部分建立新的 String 物件,以及如何建立包含單一字元多個專案的新 String 物件。
// 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
let szGreekAlpha = String('\u0391',5)
// Create a Unicode String with a Greek Omega character
let szGreekOmega = String([| '\u03A9'; '\u03A9'; '\u03A9' |],2,1)
let szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone())
// Examine the result
printfn $"{szGreekLetters}"
// The first index of Alpha
let ialpha = szGreekLetters.IndexOf '\u0391'
// The last index of Omega
let iomega = szGreekLetters.LastIndexOf '\u03A9'
printfn $"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:使用字元陣列的指標
下列範例示範如何從字元陣列的指標建立新的 String 物件。 C# 範例必須使用編譯器參數進行編譯 /unsafe
。
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!
#nowarn "9"
open System
let characters =
[| 'H'; 'e'; 'l'; 'l'; 'o'; ' '
'w'; 'o'; 'r'; 'l'; 'd'; '!'; '\u0000' |]
let value =
use charPtr = fixed characters
String charPtr
printfn $"{value}"
// The example displays the following output:
// Hello world!
範例 5:從指標和陣列範圍具現化字串
下列範例會檢查字元陣列的專案期間或驚嘆號。 如果找到字串,它會從陣列中位於標點符號前面的字元具現化字串。 如果沒有,它會具現化具有陣列整個內容的字串。 C# 範例必須使用編譯器參數進行編譯 /unsafe
。
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
#nowarn "9"
open System
open FSharp.NativeInterop
let characters =
[| 'H'; 'e'; 'l'; 'l'; 'o'; ' '
'w'; 'o'; 'r'; 'l'; 'd'; '!'; '\u0000' |]
[<EntryPoint>]
let main _ =
use charPtr = fixed characters
let mutable length = 0
let mutable iterator = charPtr
let mutable broken = false
while not broken && NativePtr.read iterator <> '\u0000' do
if NativePtr.read iterator = '!' || NativePtr.read iterator = '.' then
broken <- true
else
iterator <- NativePtr.add iterator 1
length <- length + 1
String(charPtr, 0, length)
|> printfn "%s"
0
// The example displays the following output:
// Hello World
範例 6:將字串從指標具現化為帶正負號的位元組陣列
下列範例示範如何使用 建構函式建立 類別 String(SByte*) 的 String 實例。
// 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") );
}
// Null terminated ASCII characters in an sbyte array
let szAsciiUpper =
let sbArr1 = [| 0x41y; 0x42y; 0x43y; 0x00y |]
// Instruct the Garbage Collector not to move the memory
use pAsciiUpper = fixed sbArr1
String pAsciiUpper
let szAsciiLower =
let sbArr2 = [| 0x61y; 0x62y; 0x63y; 0x00y |]
// Instruct the Garbage Collector not to move the memory
use pAsciiLower = fixed sbArr2
String(pAsciiLower, 0, sbArr2.Length)
// Prints "ABC abc"
printfn $"{szAsciiUpper} {szAsciiLower}"
// Compare Strings - the result is true
printfn $"The Strings are equal when capitalized ? %b{String.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper()) = 0}"
// This is the effective equivalent of another Compare method, which ignores case
printfn $"The Strings are equal when capitalized ? %b{String.Compare(szAsciiUpper, szAsciiLower, true) = 0}"
String(Char*)
重要
此 API 不符合 CLS 規範。
將 String 類別的新執行個體初始化為 Unicode 字元陣列的指定指標所指示的值。
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*
Unicode 字元之 Null 終端陣列的指標
- 屬性
例外狀況
目前的處理序沒有讀取所有定址字元的權限。
value
指定包含無效 Unicode 字元的陣列,或 value
指定小於 64000 的位址。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
String(Char[])
將 String 類別新執行個體初始化為所指定字元陣列中指出的 Unicode 字元。
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 字元陣列。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
String(ReadOnlySpan<Char>)
將 String 類別新執行個體初始化為所指定唯讀範圍中指出的 Unicode 字元。
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 字元的唯讀範圍。
適用於
String(SByte*)
重要
此 API 不符合 CLS 規範。
將 String 類別的新執行個體初始化為 8 位元帶正負號整數 (Signed Integer) 陣列的指標所指示的值。
public:
String(System::SByte* value);
[System.CLSCompliant(false)]
public String (sbyte* value);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value);
[<System.CLSCompliant(false)>]
new string : nativeptr<sbyte> -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<sbyte> -> string
參數
- 屬性
例外狀況
value
為 null
。
無法使用 value
初始化 String 的新執行個體,假設 value
是 ANSI 編碼。
要初始化的新字串長度,由 value
之 null 結束字元所決定,該長度太長而無法配置。
value
指定了無效的位址。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
String(Char, Int32)
將 String 類別的新執行個體初始化為由重複指定次數的指定 Unicode 字元所指示的值。
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 字元。
- count
- Int32
c
發生的次數。
例外狀況
count
小於零。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
String(Char*, Int32, Int32)
重要
此 API 不符合 CLS 規範。
將 String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置以及長度等等的指定指標所指示的值。
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 字元陣列的指標。
- startIndex
- Int32
開始位置在 value
內。
- length
- Int32
value
內要使用的字元數。
- 屬性
例外狀況
startIndex
或 length
小於零、value
+ startIndex
導致指標溢位,或目前的處理序沒有所有定址字元的讀取權限。
value
指定包含無效 Unicode 字元的陣列,或 value
+ startIndex
指定小於 64000 的位址。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
String(Char[], Int32, Int32)
將 String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置和長度等等所指示的值。
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 字元陣列。
- startIndex
- Int32
開始位置在 value
內。
- length
- Int32
value
內要使用的字元數。
例外狀況
value
為 null
。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
String(SByte*, Int32, Int32)
重要
此 API 不符合 CLS 規範。
將 String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置和長度的指定指標所指示的值。
public:
String(System::SByte* value, int startIndex, int length);
[System.CLSCompliant(false)]
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
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<sbyte> * int * int -> string
參數
- startIndex
- Int32
開始位置在 value
內。
- length
- Int32
value
內要使用的字元數。
- 屬性
例外狀況
value
為 null
。
startIndex
或 length
小於零。
-或-
value
+ startIndex
指定的位址對於目前的平台而言太大,也就是位址計算溢位。
-或-
要初始化的新字串長度太大而無法配置。
value
、startIndex
和 length
共同指定了無效的位址。
備註
注意
如需這個和其他建構函式多載的範例和完整的 String
使用資訊,請參閱建 String 構函式摘要。
適用於
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);
[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
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new string : nativeptr<sbyte> * int * int * System.Text.Encoding -> string
參數
- value
- SByte*
8 位元帶正負號整數陣列的指標。
- startIndex
- Int32
開始位置在 value
內。
- length
- Int32
value
內要使用的字元數。
- enc
- Encoding
物件,指定以 value
參考之陣列的編碼方式。 如果 enc
為 null
,則假設使用 ANSI 編碼方式。
- 屬性
例外狀況
value
為 null
。
startIndex
或 length
小於零。
-或-
value
+ startIndex
指定的位址對於目前的平台而言太大,也就是位址計算溢位。
-或-
要初始化的新字串長度太大而無法配置。
value
、startIndex
和 length
共同指定了無效的位址。
備註
注意
如需有關這個和其他 String
建構函式多載的範例和完整的使用方式資訊,請參閱建 String 構函式摘要。
適用於
意見反應
提交並檢視相關的意見反應