String 類別

定義

以 UTF-16 程式代碼單位序列表示文字。

public ref class System::String sealed : IComparable, IComparable<System::String ^>, IConvertible, IEquatable<System::String ^>, System::Collections::Generic::IEnumerable<char>
public ref class System::String sealed : ICloneable, IComparable, IComparable<System::String ^>, IConvertible, IEquatable<System::String ^>, IParsable<System::String ^>, ISpanParsable<System::String ^>, System::Collections::Generic::IEnumerable<char>
public ref class System::String sealed : ICloneable, IComparable, IComparable<System::String ^>, IConvertible, IEquatable<System::String ^>, System::Collections::Generic::IEnumerable<char>
public ref class System::String sealed : ICloneable, IComparable, IConvertible, System::Collections::IEnumerable
public ref class System::String sealed : IComparable, IComparable<System::String ^>, IEquatable<System::String ^>, System::Collections::IEnumerable
public ref class System::String sealed : IComparable, IComparable<System::String ^>, IEquatable<System::String ^>, System::Collections::Generic::IEnumerable<char>
public sealed class String : IComparable, IComparable<string>, IConvertible, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
public sealed class String : ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>, IParsable<string>, ISpanParsable<string>, System.Collections.Generic.IEnumerable<char>
public sealed class String : ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
[System.Serializable]
public sealed class String : ICloneable, IComparable, IConvertible, System.Collections.IEnumerable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class String : ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
public sealed class String : IComparable, IComparable<string>, IEquatable<string>, System.Collections.IEnumerable
public sealed class String : IComparable, IComparable<string>, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
type string = class
    interface seq<char>
    interface IEnumerable
    interface IComparable
    interface IComparable<string>
    interface IConvertible
    interface IEquatable<string>
type string = class
    interface seq<char>
    interface IEnumerable
    interface ICloneable
    interface IComparable
    interface IComparable<string>
    interface IConvertible
    interface IEquatable<string>
    interface IParsable<string>
    interface ISpanParsable<string>
type string = class
    interface seq<char>
    interface IEnumerable
    interface ICloneable
    interface IComparable
    interface IComparable<string>
    interface IConvertible
    interface IEquatable<string>
type string = class
    interface seq<char>
    interface IEnumerable
    interface IComparable
    interface IComparable<string>
    interface IConvertible
    interface IEquatable<string>
    interface ICloneable
[<System.Serializable>]
type string = class
    interface IComparable
    interface ICloneable
    interface IConvertible
    interface IEnumerable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type string = class
    interface IComparable
    interface ICloneable
    interface IConvertible
    interface IComparable<string>
    interface seq<char>
    interface IEnumerable
    interface IEquatable<string>
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type string = class
    interface IComparable
    interface ICloneable
    interface IConvertible
    interface IEnumerable
    interface IComparable<string>
    interface seq<char>
    interface IEquatable<string>
type string = class
    interface IEnumerable
    interface IComparable
    interface IComparable<string>
    interface IEquatable<string>
type string = class
    interface IComparable
    interface IComparable<string>
    interface IEquatable<string>
    interface seq<char>
    interface IEnumerable
Public NotInheritable Class String
Implements IComparable, IComparable(Of String), IConvertible, IEnumerable(Of Char), IEquatable(Of String)
Public NotInheritable Class String
Implements ICloneable, IComparable, IComparable(Of String), IConvertible, IEnumerable(Of Char), IEquatable(Of String), IParsable(Of String), ISpanParsable(Of String)
Public NotInheritable Class String
Implements ICloneable, IComparable, IComparable(Of String), IConvertible, IEnumerable(Of Char), IEquatable(Of String)
Public NotInheritable Class String
Implements ICloneable, IComparable, IConvertible, IEnumerable
Public NotInheritable Class String
Implements IComparable, IComparable(Of String), IEnumerable, IEquatable(Of String)
Public NotInheritable Class String
Implements IComparable, IComparable(Of String), IEnumerable(Of Char), IEquatable(Of String)
繼承
String
屬性
實作

備註

字串是用來表示文字之字元的循序集合。 String對像是代表字串之System.Char物件的循序集合;System.Char對象對應至UTF-16程式碼單位。 物件的值 String 是物件循序集合 System.Char 的內容,而該值是不可變的(也就是說,它是唯讀的)。 如需字串不變性的詳細資訊,請參閱 Immutability 和 StringBuilder 類別 一節。 記憶體中物件的大小 String 上限為 2 GB,或大約 10 億個字元。

如需 Unicode、UTF-16、程式代碼單位、字碼點和 CharRune 類型的詳細資訊,請參閱 .NET 中的字元編碼簡介。

具現化 String 物件

您可以透過下列方式具現化 String 物件:

  • 將字串常值賦給 String 變數。 這是用來建立字串的最常見方法。 下列範例會使用指派來建立數個字串。 請注意,在 C# 和 F# 中,因為反斜杠 (\) 是逸出字元,因此字串中的常值反斜杠必須逸出,否則整個字串必須是 @-quoted。

    string string1 = "This is a string created by assignment.";
    Console.WriteLine(string1);
    string string2a = "The path is C:\\PublicDocuments\\Report1.doc";
    Console.WriteLine(string2a);
    string string2b = @"The path is C:\PublicDocuments\Report1.doc";
    Console.WriteLine(string2b);
    // The example displays the following output:
    //       This is a string created by assignment.
    //       The path is C:\PublicDocuments\Report1.doc
    //       The path is C:\PublicDocuments\Report1.doc
    
    let string1 = "This is a string created by assignment."
    printfn "%s" string1
    let string2a = "The path is C:\\PublicDocuments\\Report1.doc"
    printfn "%s" string2a
    let string2b = @"The path is C:\PublicDocuments\Report1.doc"
    printfn "%s" string2b
    // The example displays the following output:
    //       This is a string created by assignment.
    //       The path is C:\PublicDocuments\Report1.doc
    //       The path is C:\PublicDocuments\Report1.doc
    
    Dim string1 As String = "This is a string created by assignment."
    Console.WriteLine(string1)
    Dim string2 As String = "The path is C:\PublicDocuments\Report1.doc"
    Console.WriteLine(string2)
    ' The example displays the following output:
    '       This is a string created by assignment.
    '       The path is C:\PublicDocuments\Report1.doc
    
  • 藉由呼叫類別建構函式。 下列範例會藉由呼叫數個類別建構函式來具現化字串。 請注意,某些建構函式包含字元陣列的指標或有符號位元組陣列作為參數。 Visual Basic 不支援呼叫這些建構函式。 如需建 String 構函式的詳細資訊,請參閱建 String 構函式摘要。

    char[] chars = { 'w', 'o', 'r', 'd' };
    sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
    
    // Create a string from a character array.
    string string1 = new string(chars);
    Console.WriteLine(string1);
    
    // Create a string that consists of a character repeated 20 times.
    string string2 = new string('c', 20);
    Console.WriteLine(string2);
    
    string stringFromBytes = null;
    string stringFromChars = null;
    unsafe
    {
       fixed (sbyte* pbytes = bytes)
       {
          // Create a string from a pointer to a signed byte array.
          stringFromBytes = new string(pbytes);
       }
       fixed (char* pchars = chars)
       {
          // Create a string from a pointer to a character array.
          stringFromChars = new string(pchars);
       }
    }
    Console.WriteLine(stringFromBytes);
    Console.WriteLine(stringFromChars);
    // The example displays the following output:
    //       word
    //       cccccccccccccccccccc
    //       ABCDE
    //       word
    
    let chars = [| 'w'; 'o'; 'r'; 'd' |]
    let bytes = [| 0x41y; 0x42y; 0x43y; 0x44y; 0x45y; 0x00y |]
    
    // Create a string from a character array.
    let string1 = String chars
    printfn "%s" string1
    
    // Create a string that consists of a character repeated 20 times.
    let string2 = String('c', 20)
    printfn "%s" string2
    
    let stringFromBytes =
        // Create a string from a pointer to a signed byte array.
        use pbytes = fixed bytes
        String pbytes
    let stringFromChars = 
        // Create a string from a pointer to a character array.
        use pchars = fixed chars
        String pchars
    
    printfn $"{stringFromBytes}"
    printfn $"{stringFromChars}"
    // The example displays the following output:
    //       word
    //       cccccccccccccccccccc
    //       ABCDE
    //       word
    
    Dim chars() As Char = {"w"c, "o"c, "r"c, "d"c}
    
    ' Create a string from a character array.
    Dim string1 As New String(chars)
    Console.WriteLine(string1)
    
    ' Create a string that consists of a character repeated 20 times.
    Dim string2 As New String("c"c, 20)
    Console.WriteLine(string2)
    ' The example displays the following output:
    '       word
    '       cccccccccccccccccccc
    
  • 使用字串串連運算符(在 C# 和 F# 中為 + ,在 Visual Basic 中則為 & 或 +),可以將任何 實例與字串常值的組合組合成單一字串。 下列範例說明字串串連運算子的使用。

    string string1 = "Today is " + DateTime.Now.ToString("D") + ".";
    Console.WriteLine(string1);
    
    string string2 = "This is one sentence. " + "This is a second. ";
    string2 += "This is a third sentence.";
    Console.WriteLine(string2);
    // The example displays output like the following:
    //    Today is Tuesday, July 06, 2011.
    //    This is one sentence. This is a second. This is a third sentence.
    
    let string1 = "Today is " + DateTime.Now.ToString("D") + "."
    printfn $"{string1}"
    
    let string2 = "This is one sentence. " + "This is a second. "
    let string2 = string2 + "This is a third sentence."
    printfn $"{string2}"
    // The example displays output like the following:
    //    Today is Tuesday, July 06, 2011.
    //    This is one sentence. This is a second. This is a third sentence.
    
    Dim string1 As String = "Today is " + Date.Now.ToString("D") + "."
    Console.WriteLine(string1)
    Dim string2 As String = "This is one sentence. " + "This is a second. "
    string2 += "This is a third sentence."
    Console.WriteLine(string2)
    ' The example displays output like the following:
    '    Today is Tuesday, July 06, 2011.
    '    This is one sentence. This is a second. This is a third sentence.
    
  • 透過擷取屬性或呼叫用來傳回字串的方法。 下列範例會使用 類別的方法 String ,從較大的字串擷取子字串。

    string sentence = "This sentence has five words.";
    // Extract the second word.
    int startPosition = sentence.IndexOf(" ") + 1;
    string word2 = sentence.Substring(startPosition,
                                      sentence.IndexOf(" ", startPosition) - startPosition);
    Console.WriteLine("Second word: " + word2);
    // The example displays the following output:
    //       Second word: sentence
    
    let sentence = "This sentence has five words."
    // Extract the second word.
    let startPosition = sentence.IndexOf " " + 1
    let word2 = 
        sentence.Substring(startPosition, sentence.IndexOf(" ", startPosition) - startPosition)
    printfn $"Second word: {word2}"
    // The example displays the following output:
    //       Second word: sentence
    
    Dim sentence As String = "This sentence has five words."
    ' Extract the second word.
    Dim startPosition As Integer = sentence.IndexOf(" ") + 1
    Dim word2 As String = sentence.Substring(startPosition,
                                           sentence.IndexOf(" ", startPosition) - startPosition)
    Console.WriteLine("Second word: " + word2)
    ' The example displays the following output:
    '       Second word: sentence
    
  • 藉由呼叫格式化方法,將值或物件轉換成其字串表示。 下列範例會使用 複合格式 設定功能,將兩個物件的字串表示內嵌至字串中。

    DateTime dateAndTime = new DateTime(2011, 7, 6, 7, 32, 0);
    double temperature = 68.3;
    string result = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
                                  dateAndTime, temperature);
    Console.WriteLine(result);
    // The example displays the following output:
    //       At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.
    
    let dateAndTime = DateTime(2011, 7, 6, 7, 32, 0)
    let temperature = 68.3
    String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.", dateAndTime, temperature)
    |> printfn "%s"
    // The example displays the following output:
    //       At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.
    
    Dim dateAndTime As DateTime = #07/06/2011 7:32:00AM#
    Dim temperature As Double = 68.3
    Dim result As String = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
                                       dateAndTime, temperature)
    Console.WriteLine(result)
    ' The example displays the following output:
    '       At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.
    

Char 物件和 Unicode 字元

字串中的每個字元都是由 Unicode 純量值所定義,也稱為 Unicode 字碼點或 Unicode 字元的序數(數值) 值。 每個程式代碼點都會使用UTF-16編碼來編碼,編碼的每個元素的數值會以 Char 物件表示。

Note

請注意,由於 String 實例是由UTF-16程式代碼單位的循序集合所組成,因此可以建立 String 格式不正確 Unicode 字元串的物件。 例如,可以建立具有低代理且沒有對應高代理的字串。 雖然某些方法,例如命名空間中的 System.Text 編碼和譯碼物件方法,可能會執行檢查以確保字串格式良好, String 類別成員不會確保字串的格式良好。

Char 一物件通常代表單一程式代碼點;也就是說,的 Char 數值等於程式代碼點。 例如,字元 「a」 的代碼點是 U+0061。 不過,代碼點可能需要超過一個的編碼元素(超過一個 Char 物件)。 Unicode 標準會定義兩種類型的字元,這些字元對應至多個 Char 物件:graphemes 和 Unicode 增補代碼點,這些字元對應至 Unicode 增補平面中的字元。

  • 圖文符由基底字元表示,後面接著一個或多個結合字元。 例如,字元 ä 是由 Char 代碼點為 U+0061 的物件表示,後面接著代碼 Char 點為 U+0308 的物件。 這個字元也可以由具有U+00E4代碼點的單 Char 一物件定義。 如下列範例所示,區分文化特性的相等比較表示法表示這兩個表示法相等,但一般序數比較則不相同。 不過,如果兩個字串正規化,序數比較也表示它們相等。 (如需正規化字串的詳細資訊,請參閱 正規化 區段。)

    using System;
    using System.Globalization;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\graphemes.txt");
          string grapheme = "\u0061\u0308";
          sw.WriteLine(grapheme);
          
          string singleChar = "\u00e4";
          sw.WriteLine(singleChar);
                
          sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                       String.Equals(grapheme, singleChar, 
                                     StringComparison.CurrentCulture));
          sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar, 
                       String.Equals(grapheme, singleChar, 
                                     StringComparison.Ordinal));
          sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar, 
                       String.Equals(grapheme.Normalize(), 
                                     singleChar.Normalize(), 
                                     StringComparison.Ordinal));
          sw.Close(); 
       }
    }
    // The example produces the following output:
    //       ä
    //       ä
    //       ä = ä (Culture-sensitive): True
    //       ä = ä (Ordinal): False
    //       ä = ä (Normalized Ordinal): True
    
    open System
    open System.IO
    
    do
        use sw = new StreamWriter(@".\graphemes.txt")
        let grapheme = "\u0061\u0308"
        sw.WriteLine grapheme
    
        let singleChar = "\u00e4"
        sw.WriteLine singleChar
    
        sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                    String.Equals(grapheme, singleChar,
                                    StringComparison.CurrentCulture))
        sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar,
                    String.Equals(grapheme, singleChar,
                                    StringComparison.Ordinal))
        sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar,
                    String.Equals(grapheme.Normalize(),
                                    singleChar.Normalize(),
                                    StringComparison.Ordinal))
    // The example produces the following output:
    //       ä
    //       ä
    //       ä = ä (Culture-sensitive): True
    //       ä = ä (Ordinal): False
    //       ä = ä (Normalized Ordinal): True
    
    Imports System.Globalization
    Imports System.IO
    
    Module Example9
        Public Sub Main()
            Dim sw As New StreamWriter(".\graphemes.txt")
            Dim grapheme As String = ChrW(&H61) + ChrW(&H308)
            sw.WriteLine(grapheme)
    
            Dim singleChar As String = ChrW(&HE4)
            sw.WriteLine(singleChar)
    
            sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar,
                       String.Equals(grapheme, singleChar,
                                     StringComparison.CurrentCulture))
            sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar,
                       String.Equals(grapheme, singleChar,
                                     StringComparison.Ordinal))
            sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar,
                       String.Equals(grapheme.Normalize(),
                                     singleChar.Normalize(),
                                     StringComparison.Ordinal))
            sw.Close()
        End Sub
    End Module
    ' The example produces the following output:
    '       ä
    '       ä
    '       ä = ä (Culture-sensitive): True
    '       ä = ä (Ordinal): False
    '       ä = ä (Normalized Ordinal): True
    
  • Unicode 增補碼位(代理對)由一個碼位是高位代理的 Char 物件表示,接著是一個碼位是低位代理的 Char 物件。 高位代理對的程式碼單位範圍從U+D800到U+DBFF。 低位代理對的代碼單位範圍從U+DC00到U+DFFF。 Surrogate 字組用來代表 16 個 Unicode 增補平面中的字元。 下列範例會建立 Surrogate 字元,並將它 Char.IsSurrogatePair(Char, Char) 傳遞給 方法,以判斷它是否為 Surrogate 字組。

    string surrogate = "\uD800\uDC03";
    for (int ctr = 0; ctr < surrogate.Length; ctr++) 
       Console.Write($"U+{(ushort)surrogate[ctr]:X2} ");
    
    Console.WriteLine();
    Console.WriteLine("   Is Surrogate Pair: {0}", 
                      Char.IsSurrogatePair(surrogate[0], surrogate[1]));
    // The example displays the following output:
    //       U+D800 U+DC03
    //          Is Surrogate Pair: True
    
    open System
    
    let surrogate = "\uD800\uDC03"
    for i = 0 to surrogate.Length - 1 do
        printf $"U+{uint16 surrogate[i]:X2} "
    
    printfn $"\n   Is Surrogate Pair: {Char.IsSurrogatePair(surrogate[0], surrogate[1])}"
    // The example displays the following output:
    //       U+D800 U+DC03
    //          Is Surrogate Pair: True
    
    Module Example20
        Public Sub Main()
            Dim surrogate As String = ChrW(&HD800) + ChrW(&HDC03)
            For ctr As Integer = 0 To surrogate.Length - 1
                Console.Write("U+{0:X2} ", Convert.ToUInt16(surrogate(ctr)))
            Next
            Console.WriteLine()
            Console.WriteLine("   Is Surrogate Pair: {0}",
                            Char.IsSurrogatePair(surrogate(0), surrogate(1)))
        End Sub
    End Module
    
    ' The example displays the following output:
    '       U+D800 U+DC03
    '          Is Surrogate Pair: True
    

Unicode 標準

字串中的字元會以對應至 Char 值的 UTF-16 編碼程式代碼單位表示。

字串中的每個字元都有相關聯的 Unicode 字元類別目錄,此類別目錄由 UnicodeCategory 列舉以 .NET 表示。 您可以呼叫CharUnicodeInfo.GetUnicodeCategory方法來判斷字元或代理對的類別。

.NET 會維護自己的字元表及其對應的分類,以確保在不同平台上執行的特定 .NET 實作,都能傳回一致的字元類別資訊。 在所有 .NET 版本和所有OS平臺上,Unicode 字元資料庫提供字元類別資訊。

下表列出 .NET 版本及其字元分類依據的 Unicode 標準版本。

.NET 版本 Unicode Standard 版本
.NET 框架 1.1 Unicode Standard 4.0.0 版
.NET 框架 2.0 Unicode Standard 5.0.0 版
.NET 框架 3.5 Unicode Standard 5.0.0 版
.NET 架構 4 Unicode Standard 5.0.0 版
.NET 框架 4.5 Unicode Standard 6.3.0 版
.NET 框架 4.5.1 Unicode Standard 6.3.0 版
.NET 框架 4.5.2 Unicode Standard 6.3.0 版
.NET 框架 4.6 Unicode Standard 6.3.0 版
.NET 框架 4.6.1 Unicode Standard 6.3.0 版
.NET framework 4.6.2 及更新版本 Unicode Standard 8.0.0 版
.NET 核心 2.1 Unicode Standard 8.0.0 版
.NET 核心 3.1 Unicode Standard 11.0.0 版
.NET 5 Unicode Standard 13.0.0 版

此外,.NET 支援以 Unicode 標準為基礎的字串比較和排序。 字串比較與排序資訊由 International Components for Unicode 函式庫提供(2019 年 5 月 Windows 10 更新前的 Windows 版本除外)。

內嵌「Null」字元

在 .NET 中 String ,物件可以包含內嵌的 Null 字元,其會算作字串長度的一部分。 不過,在某些語言中,例如 C 和 C++,null 字元表示字串的結尾;它不會被視為字串的一部分,而且不會計入字串長度的一部分。 這表示當 C 和 C++ 程式設計人員或以 C 或 C++ 撰寫的函式庫套用至 String 物件時,他們對字串可能做出的下列常見假設不一定有效:

  • strlenwcslen 函式傳回的值不一定等於 String.Length

  • strcpy_s 函式所建立的wcscpy_s字串不一定與複製的字串相同。

您應該確保原生 C 和 C++ 的代碼,無論是具現化 String 的物件,還是透過平台調用傳遞 String 的物件,不要假設嵌入的 "Null" 字元會標誌字串結尾。

當字串排序(或比較)和搜尋字串時,字串中的內嵌 Null 字元也會以不同的方式處理。 執行兩個字串之間的區分文化特性比較時,包括使用不因文化特性而異的比較,會忽略空字元。 它們被視為僅用於不區分大小寫的序數比較。 另一方面,使用 ContainsStartsWithIndexOf 方法搜尋字串時,一律會考慮內嵌的 Null 字元。

字串和索引

索引是Char物件在String中的位置(不是 Unicode 字元)。 索引是以零起始的非負數,從字串中的第一個位置開始,也就是索引位置為零。 一些搜尋方法,例如 IndexOfLastIndexOf,會傳回字串實例中字元或子字串的索引。

屬性 Chars[Int32] 可讓您依字串中的索引位置存取個別 Char 物件。 Chars[Int32]因為 屬性是預設屬性 (在 Visual Basic 中) 或索引器 (在 C# 和 F# 中),因此您可以使用下列程式代碼來存取字串中的個別Char物件。 此程式代碼會在字串中尋找空格符或標點符號字元,以判斷字串包含的字數。

string s1 = "This string consists of a single short sentence.";
int nWords = 0;

s1 = s1.Trim();      
for (int ctr = 0; ctr < s1.Length; ctr++) {
   if (Char.IsPunctuation(s1[ctr]) | Char.IsWhiteSpace(s1[ctr]))
      nWords++;              
}
Console.WriteLine("The sentence\n   {0}\nhas {1} words.",
                  s1, nWords);                                                                     
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
let s1 = "This string consists of a single short sentence."
let mutable nWords = 0

for i = 0 to s1.Length - 1 do
    if Char.IsPunctuation s1[i] || Char.IsWhiteSpace s1[i] then
        nWords <- nWords + 1
printfn $"The sentence\n   {s1}\nhas {nWords} words."
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
Module Example12
    Public Sub Main()
        Dim s1 As String = "This string consists of a single short sentence."
        Dim nWords As Integer = 0

        s1 = s1.Trim()
        For ctr As Integer = 0 To s1.Length - 1
            If Char.IsPunctuation(s1(ctr)) Or Char.IsWhiteSpace(s1(ctr)) Then
                nWords += 1
            End If
        Next
        Console.WriteLine("The sentence{2}   {0}{2}has {1} words.",
                        s1, nWords, vbCrLf)
    End Sub
End Module
' The example displays the following output:
'       The sentence
'          This string consists of a single short sentence.
'       has 8 words.

String因為 類別會實作 IEnumerable 介面,所以您也可以使用 Char 建構逐一查看foreach字串中的物件,如下列範例所示。

string s1 = "This string consists of a single short sentence.";
int nWords = 0;

s1 = s1.Trim();      
foreach (var ch in s1) {
   if (Char.IsPunctuation(ch) | Char.IsWhiteSpace(ch))
      nWords++;              
}
Console.WriteLine("The sentence\n   {0}\nhas {1} words.",
                  s1, nWords);                                                                     
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
let s1 = "This string consists of a single short sentence."
let mutable nWords = 0

for ch in s1 do
    if Char.IsPunctuation ch || Char.IsWhiteSpace ch then
        nWords <- nWords + 1
printfn $"The sentence\n   {s1}\nhas {nWords} words."
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
Module Example13
    Public Sub Main()
        Dim s1 As String = "This string consists of a single short sentence."
        Dim nWords As Integer = 0

        s1 = s1.Trim()
        For Each ch In s1
            If Char.IsPunctuation(ch) Or Char.IsWhiteSpace(ch) Then
                nWords += 1
            End If
        Next
        Console.WriteLine("The sentence{2}   {0}{2}has {1} words.",
                        s1, nWords, vbCrLf)
    End Sub
End Module
' The example displays the following output:
'       The sentence
'          This string consists of a single short sentence.
'       has 8 words.

連續索引值可能不會對應到連續的 Unicode 字元,因為 Unicode 字元可能會編碼為多個 Char 物件。 特別是,字串可能包含多字元單位的文字,這些文字是由基底字元所組成,後面接著一或多個結合字元或代理組。 若要使用 Unicode 字元而非 Char 物件,請使用 System.Globalization.StringInfoTextElementEnumerator 類別,或 String.EnumerateRunes 方法和 Rune 結構。 下列範例說明與物件搭配運作 Char 的程式代碼與使用 Unicode 字元的程式代碼之間的差異。 它會比較句子中每一個單字中的字元或文字元素數目。 字串包含基底字元後接結合字元的兩個序列。

// First sentence of The Mystery of the Yellow Room, by Leroux.
string opening = "Ce n'est pas sans une certaine émotion que "+
                 "je commence à raconter ici les aventures " +
                 "extraordinaires de Joseph Rouletabille."; 
// Character counters.
int nChars = 0;
// Objects to store word count.
List<int> chars = new List<int>();
List<int> elements = new List<int>();

foreach (var ch in opening) {
   // Skip the ' character.
   if (ch == '\u0027') continue;
        
   if (Char.IsWhiteSpace(ch) | (Char.IsPunctuation(ch))) {
      chars.Add(nChars);
      nChars = 0;
   }
   else {
      nChars++;
   }
}

System.Globalization.TextElementEnumerator te = 
   System.Globalization.StringInfo.GetTextElementEnumerator(opening);
while (te.MoveNext()) {
   string s = te.GetTextElement();   
   // Skip the ' character.
   if (s == "\u0027") continue;
   if ( String.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && Char.IsPunctuation(Convert.ToChar(s)))) {
      elements.Add(nChars);         
      nChars = 0;
   }
   else {
      nChars++;
   }
}

// Display character counts.
Console.WriteLine("{0,6} {1,20} {2,20}",
                  "Word #", "Char Objects", "Characters"); 
for (int ctr = 0; ctr < chars.Count; ctr++) 
   Console.WriteLine("{0,6} {1,20} {2,20}",
                     ctr, chars[ctr], elements[ctr]); 
// The example displays the following output:
//       Word #         Char Objects           Characters
//            0                    2                    2
//            1                    4                    4
//            2                    3                    3
//            3                    4                    4
//            4                    3                    3
//            5                    8                    8
//            6                    8                    7
//            7                    3                    3
//            8                    2                    2
//            9                    8                    8
//           10                    2                    1
//           11                    8                    8
//           12                    3                    3
//           13                    3                    3
//           14                    9                    9
//           15                   15                   15
//           16                    2                    2
//           17                    6                    6
//           18                   12                   12
open System
open System.Globalization

// First sentence of The Mystery of the Yellow Room, by Leroux.
let opening = "Ce n'est pas sans une certaine émotion que je commence à raconter ici les aventures extraordinaires de Joseph Rouletabille."
// Character counters.
let mutable nChars = 0
// Objects to store word count.
let chars = ResizeArray<int>()
let elements = ResizeArray<int>()

for ch in opening do
    // Skip the ' character.
    if ch <> '\u0027' then
        if Char.IsWhiteSpace ch || Char.IsPunctuation ch then
            chars.Add nChars
            nChars <- 0
        else
            nChars <- nChars + 1

let te = StringInfo.GetTextElementEnumerator opening
while te.MoveNext() do
    let s = te.GetTextElement()
    // Skip the ' character.
    if s <> "\u0027" then
        if String.IsNullOrEmpty(s.Trim()) || (s.Length = 1 && Char.IsPunctuation(Convert.ToChar s)) then
            elements.Add nChars
            nChars <- 0
        else
            nChars <- nChars + 1

// Display character counts.
printfn "%6s %20s %20s" "Word #" "Char Objects " "Characters"
for i = 0 to chars.Count - 1 do
    printfn "%6d %20d %20d" i chars[i] elements[i]
// The example displays the following output:
//       Word #         Char Objects           Characters
//            0                    2                    2
//            1                    4                    4
//            2                    3                    3
//            3                    4                    4
//            4                    3                    3
//            5                    8                    8
//            6                    8                    7
//            7                    3                    3
//            8                    2                    2
//            9                    8                    8
//           10                    2                    1
//           11                    8                    8
//           12                    3                    3
//           13                    3                    3
//           14                    9                    9
//           15                   15                   15
//           16                    2                    2
//           17                    6                    6
//           18                   12                   12
Imports System.Collections.Generic
Imports System.Globalization

Module Example14
    Public Sub Main()
        ' First sentence of The Mystery of the Yellow Room, by Leroux.
        Dim opening As String = "Ce n'est pas sans une certaine émotion que " +
                              "je commence à raconter ici les aventures " +
                              "extraordinaires de Joseph Rouletabille."
        ' Character counters.
        Dim nChars As Integer = 0
        ' Objects to store word count.
        Dim chars As New List(Of Integer)()
        Dim elements As New List(Of Integer)()

        For Each ch In opening
            ' Skip the ' character.
            If ch = ChrW(&H27) Then Continue For

            If Char.IsWhiteSpace(ch) Or Char.IsPunctuation(ch) Then
                chars.Add(nChars)
                nChars = 0
            Else
                nChars += 1
            End If
        Next

        Dim te As TextElementEnumerator = StringInfo.GetTextElementEnumerator(opening)
        Do While te.MoveNext()
            Dim s As String = te.GetTextElement()
            ' Skip the ' character.
            If s = ChrW(&H27) Then Continue Do
            If String.IsNullOrEmpty(s.Trim()) Or (s.Length = 1 AndAlso Char.IsPunctuation(Convert.ToChar(s))) Then
                elements.Add(nChars)
                nChars = 0
            Else
                nChars += 1
            End If
        Loop

        ' Display character counts.
        Console.WriteLine("{0,6} {1,20} {2,20}",
                        "Word #", "Char Objects", "Characters")
        For ctr As Integer = 0 To chars.Count - 1
            Console.WriteLine("{0,6} {1,20} {2,20}",
                           ctr, chars(ctr), elements(ctr))
        Next
    End Sub
End Module
' The example displays the following output:
'    Word #         Char Objects           Characters
'         0                    2                    2
'         1                    4                    4
'         2                    3                    3
'         3                    4                    4
'         4                    3                    3
'         5                    8                    8
'         6                    8                    7
'         7                    3                    3
'         8                    2                    2
'         9                    8                    8
'        10                    2                    1
'        11                    8                    8
'        12                    3                    3
'        13                    3                    3
'        14                    9                    9
'        15                   15                   15
'        16                    2                    2
'        17                    6                    6
'        18                   12                   12

這個範例會使用StringInfo.GetTextElementEnumerator 方法和TextElementEnumerator 類別來列舉字串中的所有文字元素。 您也可以藉由呼叫 StringInfo.ParseCombiningCharacters 方法來擷取包含每個文字元素起始索引的陣列。

如需使用文字單位而非個別 Char 值的詳細資訊,請參閱 .NET 中的字元編碼簡介。

Null 字串和空字串

已宣告但尚未指定值的字串為 null。 試圖在該字串上呼叫方法會拋出NullReferenceException。 Null 字串與空字串不同,這是值為 “” 或 String.Empty的字串。 在某些情況下,將 Null 字串或空字串作為方法呼叫的參數傳遞會引發例外。 例如,將 Null 字串傳遞至 Int32.Parse 方法會 ArgumentNullException擲回 ,而傳遞空字串會 FormatException擲回 。 在其他情況下,方法自變數可以是 Null 字串或空字串。 例如,如果您要為 IFormattable 類別提供實作,則想要將 Null 字串和空字串與一般 (“G”) 格式規範相等。

類別 String 包含下列兩種便利方法,可讓您測試字串是否為 null 或空白:

  • IsNullOrEmpty,指出字串是否為 null 或等於 String.Empty。 此方法不需要使用程式代碼,如下所示:

    if (str == null || str.Equals(String.Empty))
    
    if str = null || str.Equals String.Empty then
    
    If str Is Nothing OrElse str.Equals(String.Empty) Then
    
  • IsNullOrWhiteSpace,表示字串是否為 null、等於 String.Empty或 ,或是只包含空格符。 此方法不需要使用程式代碼,如下所示:

    if (str == null || str.Equals(String.Empty) || str.Trim().Equals(String.Empty))
    
    if str = null || str.Equals String.Empty || str.Trim().Equals String.Empty then
    
    If str Is Nothing OrElse str.Equals(String.Empty) OrElse str.Trim().Equals(String.Empty) Then
    

下列範例會使用IsNullOrEmpty方法,在IFormattable.ToString的自定義Temperature類別實作中。 方法支援 「G」、“C”、“F” 和 “K” 格式字串。 如果空格式字串或其值 null 傳遞至 方法的格式字串,其值會變更為 「G」 格式字串。

public string ToString(string format, IFormatProvider provider) 
{
   if (String.IsNullOrEmpty(format)) format = "G";  
   if (provider == null) provider = CultureInfo.CurrentCulture;
   
   switch (format.ToUpperInvariant())
   {
      // Return degrees in Celsius.    
      case "G":
      case "C":
         return temp.ToString("F2", provider) + "°C";
      // Return degrees in Fahrenheit.
      case "F": 
         return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F";
      // Return degrees in Kelvin.
      case "K":   
         return (temp + 273.15).ToString();
      default:
         throw new FormatException(
               String.Format("The {0} format string is not supported.", 
                             format));
   }                                   
}
member _.ToString(format: string, provider: IFormatProvider) =
    let format = 
        if String.IsNullOrEmpty format then "G" else format
    
    let provider: IFormatProvider = 
        if provider = null then CultureInfo.CurrentCulture else provider

    match format.ToUpperInvariant() with
    // Return degrees in Celsius.
    | "G"
    | "C" ->
        temp.ToString("F2", provider) + "°C"
    // Return degrees in Fahrenheit.
    | "F" ->
        (temp * 9. / 5. + 32.).ToString("F2", provider) + "°F"
    // Return degrees in Kelvin.
    | "K" ->
        (temp + 273.15).ToString()
    | _ ->
        raise (FormatException(String.Format("The {0} format string is not supported.",format)))
Public Overloads Function ToString(fmt As String, provider As IFormatProvider) As String _
               Implements IFormattable.ToString
    If String.IsNullOrEmpty(fmt) Then fmt = "G"
    If provider Is Nothing Then provider = CultureInfo.CurrentCulture

    Select Case fmt.ToUpperInvariant()
     ' Return degrees in Celsius.    
        Case "G", "C"
            Return temp.ToString("F2", provider) + "°C"
     ' Return degrees in Fahrenheit.
        Case "F"
            Return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F"
     ' Return degrees in Kelvin.
        Case "K"
            Return (temp + 273.15).ToString()
        Case Else
            Throw New FormatException(
              String.Format("The {0} format string is not supported.",
                            fmt))
    End Select
End Function

不變性和 StringBuilder 類別

對象 String 稱為不可變(只讀),因為它的值在建立之後無法修改。 看似修改 String 物件的方法實際上會傳回包含修改的新 String 物件。

因為字串是不可變的,所以對單一字串執行重複新增或刪除的字串操作例程可能會造成顯著的效能損失。 例如,下列程式碼使用隨機數產生器來在範圍0x0001到0x052F內建立一個包含1000個字元的字串。 雖然程式代碼似乎使用字串串連將新字元附加至名為 str的現有字串,但它實際上會為每個串連作業建立新的 String 物件。

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      
      string str = String.Empty;
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                           false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         str += (char)rnd.Next(1, 0x0530);
         if (str.Length % 60 == 0)
            str += Environment.NewLine;          
      }                    
      sw.Write(str);
      sw.Close();
   }
}
open System
open System.IO
open System.Text

do
    let rnd = Random()

    let mutable str = String.Empty
    use sw = new StreamWriter(@".\StringFile.txt", false, Encoding.Unicode)
    for _ = 0 to 1000 do
        str <- str + (rnd.Next(1, 0x0530) |> char |> string)
        if str.Length % 60 = 0 then
            str <- str + Environment.NewLine
    sw.Write str
Imports System.IO
Imports System.Text

Module Example10
    Public Sub Main()
        Dim rnd As New Random()

        Dim str As String = String.Empty
        Dim sw As New StreamWriter(".\StringFile.txt",
                           False, Encoding.Unicode)

        For ctr As Integer = 0 To 1000
            str += ChrW(rnd.Next(1, &H530))
            If str.Length Mod 60 = 0 Then str += vbCrLf
        Next
        sw.Write(str)
        sw.Close()
    End Sub
End Module

您可以針對對字串值進行多個變更的作業使用 StringBuilder 類別,而不是 String 類別。 不同於 類別的 String 實例, StringBuilder 對像是可變的;當您從字串串連、附加或刪除子字串時,作業會在單一字串上執行。 當您完成修改 物件的值 StringBuilder 時,您可以呼叫其 StringBuilder.ToString 方法,將它轉換成字元串。 下列範例將上一個範例中用來串連範圍從 0x0001 到 0x052F 的1000個隨機字元的 String 替換為 StringBuilder 物件。

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      StringBuilder sb = new StringBuilder();
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                                         false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         sb.Append((char)rnd.Next(1, 0x0530));
         if (sb.Length % 60 == 0)
            sb.AppendLine();          
      }                    
      sw.Write(sb.ToString());
      sw.Close();
   }
}
open System
open System.IO
open System.Text

do
    let rnd = Random()
    let sb = StringBuilder()
    use sw = new StreamWriter(@".\StringFile.txt", false, Encoding.Unicode)

    for _ = 0 to 1000 do
        sb.Append(rnd.Next(1, 0x0530) |> char) |> ignore
        if sb.Length % 60 = 0 then
            sb.AppendLine() |> ignore
    sw.Write(string sb)
Imports System.IO
Imports System.Text

Module Example11
    Public Sub Main()
        Dim rnd As New Random()
        Dim sb As New StringBuilder()
        Dim sw As New StreamWriter(".\StringFile.txt",
                                 False, Encoding.Unicode)

        For ctr As Integer = 0 To 1000
            sb.Append(ChrW(rnd.Next(1, &H530)))
            If sb.Length Mod 60 = 0 Then sb.AppendLine()
        Next
        sw.Write(sb.ToString())
        sw.Close()
    End Sub
End Module

序數與考慮文化差異的操作

類別 String 的成員會在 String 對象上執行序數或具文化敏感性的(語言)運算。 序數運算會處理每個 Char 物件的數值。 依文化特性調整的作業會對String物件的值進行操作,並將與該文化相關的大小寫區分、排序、格式設定和剖析規則納入考慮。 文化敏感操作會在明確宣告的文化或隱含的當前文化情境中執行。 這兩種作業在相同的字串上執行時,可能會產生非常不同的結果。

.NET 也支援不區分文化的語言字串作業,方法是使用不變文化(CultureInfo.InvariantCulture),這種文化特性鬆散地基於不受區域限制的英文文化設定。 System.Globalization.CultureInfo與其他設定不同,不變文化的設定保證在單一電腦上會保持一致性,無論是從系統到系統,還是跨 .NET 版本。 不可變的文化特性可視為一種黑箱,可確保所有文化特性的字串比較和排序的穩定性。

Important

如果您的應用程式對符號標識碼(例如檔名或命名管道)或 XML 檔案中的文字型數據等持續性數據做出安全性決策,則作業應該使用序數比較,而不是區分文化特性的比較。 這是因為區分文化特性的比較可能會根據作用中的文化特性產生不同的結果,而序數比較只取決於比較字元的二進位值。

Important

大多數執行字串作業的方法都包含一個多載,該多載具有類型StringComparison的參數,讓您可以指定方法執行的是序數作業還是區分文化特性的作業。 一般而言,您應該呼叫這個重載,以清晰呈現您方法呼叫的意圖。 如需在字串上使用序數和區分文化特性作業的最佳做法和指引,請參閱 使用字串的最佳做法。

字母大小寫處理、剖析與格式化、比較與排序以及相等性測試的作業可以是以序數或文化敏感的方式進行。 下列各節將討論每個作業類別。

Tip

您應該一律呼叫方法多載,讓方法呼叫的意圖變得清楚。 例如,與其呼叫 Compare(String, String) 方法來使用目前文化特性的慣例進行兩個字串的文化敏感比較,您應該呼叫 Compare(String, String, StringComparison) 方法,並將 StringComparison.CurrentCulture 設定為 comparisonType 的參數值。 如需詳細資訊,請參閱使用字串的最佳做法

你可以從 預設 Unicode 校對元素表下載排序權重表,這是一組包含用於排序與比較操作的字元權重資訊的文字檔。

大小寫

大小寫規則決定如何變更 Unicode 字元的大小寫;例如,從小寫到大寫。 通常,在進行字串比較之前會先執行字母大小寫轉換作業。 例如,字串可能會轉換成大寫,以便與另一個大寫字串進行比較。 您可以藉由呼叫 ToLower 或方法,將字串中的字元轉換成小寫,而且您可以呼叫 ToLowerInvariantToUpperToUpperInvariant 方法,將它們轉換成大寫。 此外,您可以使用 TextInfo.ToTitleCase 方法將字串轉換成標題大小寫。

Note

僅限 Linux 和 macOS 系統上執行的 .NET Core: C 和 Posix 文化特性的定序行為一律會區分大小寫,因為這些文化特性不會使用預期的 Unicode 定序順序。 建議您使用除了 C 或 Posix 以外的其他文化特性來執行文化敏感且不區分大小寫的排序作業。

大小寫作業可以根據目前文化特性、指定的文化特性或不因文化特性而異的規則。 因為大小寫對應可能會因所使用的文化而有所不同,所以改變大小寫的結果可能會因文化而異。 大小寫的實際差異有三種:

  • 拉丁大寫字母 I(U+0049)、拉丁小寫字母 I(U+0069)、拉丁大寫字母 I 與 DOT ABOVE (U+0130) 和拉丁小寫字母無點 I (U+0131) 的案例對應差異。 在 tr-TR(土耳其)和 az-Latn-AZ(亞塞拜然、拉丁)文化特性中,及在 tr、az 和 az-Latn 中性文化特性中,小寫相當於拉丁大寫字母 I 是拉丁無點小寫字母 I,而大寫對等的拉丁小寫字母 I 是拉丁帶點大寫字母 I。 在所有其他文化中,包括不變文化,拉丁小寫字母 I 和拉丁大寫字母 I 是小寫和大寫的對應字母。

    下列範例示範設計來防止檔案系統存取的字串比較如何因為依賴文化敏感的大小寫比較而失敗。 (應該使用不因文化特性而異的大小寫慣例。

    using System;
    using System.Globalization;
    using System.Threading;
    
    public class Example
    {
       const string disallowed = "file";
       
       public static void Main()
       {
          IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt");
       }
    
       private static void IsAccessAllowed(String resource)
       {
          CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
                                     CultureInfo.CreateSpecificCulture("tr-TR") };
          String scheme = null;
          int index = resource.IndexOfAny( new Char[] { '\\', '/' } );
          if (index > 0) 
             scheme = resource.Substring(0, index - 1);
    
          // Change the current culture and perform the comparison.
          foreach (var culture in cultures) {
             Thread.CurrentThread.CurrentCulture = culture;
             Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
             Console.WriteLine(resource);
             Console.WriteLine("Access allowed: {0}", 
                               ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase));      
             Console.WriteLine();
          }   
       }
    }
    // The example displays the following output:
    //       Culture: English (United States)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: False
    //       
    //       Culture: Turkish (Turkey)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: True
    
    open System
    open System.Globalization
    open System.Threading
    
    let disallowed = "file"
    
    let isAccessAllowed (resource: string) =
        let cultures = 
            [| CultureInfo.CreateSpecificCulture "en-US"
               CultureInfo.CreateSpecificCulture "tr-TR" |]
        let index = resource.IndexOfAny [| '\\'; '/' |]
        let scheme =
            if index > 0 then
                resource.Substring(0, index - 1)
            else 
                null
    
        // Change the current culture and perform the comparison.
        for culture in cultures do
            Thread.CurrentThread.CurrentCulture <- culture
            printfn $"Culture: {CultureInfo.CurrentCulture.DisplayName}"
            printfn $"{resource}"
            printfn $"Access allowed: {String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase) |> not}"
            printfn ""
            
    isAccessAllowed @"FILE:\\\c:\users\user001\documents\FinancialInfo.txt"
    // The example displays the following output:
    //       Culture: English (United States)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: False
    //
    //       Culture: Turkish (Turkey)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: True
    
    Imports System.Globalization
    Imports System.Threading
    
    Module Example2
        Const disallowed = "file"
    
        Public Sub Main()
            IsAccessAllowed("FILE:\\\c:\users\user001\documents\FinancialInfo.txt")
        End Sub
    
        Private Sub IsAccessAllowed(resource As String)
            Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"),
                                            CultureInfo.CreateSpecificCulture("tr-TR")}
            Dim scheme As String = Nothing
            Dim index As Integer = resource.IndexOfAny({"\"c, "/"c})
            If index > 0 Then scheme = resource.Substring(0, index - 1)
    
            ' Change the current culture and perform the comparison.
            For Each culture In cultures
                Thread.CurrentThread.CurrentCulture = culture
                Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName)
                Console.WriteLine(resource)
                Console.WriteLine("Access allowed: {0}",
                               Not String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase))
                Console.WriteLine()
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       Culture: English (United States)
    '       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    '       Access allowed: False
    '       
    '       Culture: Turkish (Turkey)
    '       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    '       Access allowed: True
    
  • 不變文化特性與所有其他文化特性之間的案例對應差異。 在這些情況下,使用不因文化特性而異的大小寫規則,將字元變更為大寫或小寫,會傳回相同的字元。 對於所有其他文化特性,它會傳回不同的字元。 下表列出部分受影響的字元。

    角色 如果已變更為 Returns
    微米符號(U+00B5) 大寫 希臘大寫字母 MU (U+-39C)
    上面有點的拉丁大寫字母 I (U+0130) 小寫 拉丁小寫字母 I (U+0069)
    拉丁小字母無點數 I (U+0131) 大寫 拉丁大寫字母 I (U+0049)
    拉丁小寫字母「長 S」(U+017F) 大寫 拉丁大寫字母 S (U+0053)
    拉丁大寫字母 D 與小字母 Z 與 CARON (U+01C5) 小寫 拉丁小字母Z與卡隆 (U+01C6)
    結合希臘文 YPOGEGRAMMENI(U+0345) 大寫 希臘大寫字母 IOTA (U+0399)
  • ASCII 字元範圍中兩個字母混合大小寫組的案例對應差異。 在大多數文化中,混合大小寫的兩個字母組合等同於對應的兩個字母大寫或小寫組合。 對於下列文化中的下列兩個字母雙而言,這並不成立,因為每種情況下,它們都會與二合字母進行比較:

    • hr-HR(克羅埃西亞)文化中的“lJ”和“nJ”。
    • cs-CZ(捷克)和 sk-SK(斯洛伐克)地區文化中的“cH”。
    • 達德克(丹麥)文化中的“aA”。
    • 胡-胡(匈牙利)文化中的 「cS」、“dZ”、“dZ”、“nY”、“sZ”、“tY” 和 “zS”。
    • “cH”和“lL”在 es-ES_tradnl(西班牙語(西班牙,傳統排序))文化中。
    • vi-VN(越南)文化中的 “cH”、“gI”、“kH”、“nG”、“nH”、“pH”、“qU'”、“tH”和“tR”。

    不過,遇到這類配對區分文化特性的比較會造成問題的情況並不常見,因為這些配對在固定字串或標識符中並不常見。

下列範例說明將字串轉換成大寫時,不同文化之間的大寫規則差異。

using System;
using System.Globalization;
using System.IO;

public class Example
{
   public static void Main()
   {
      StreamWriter sw = new StreamWriter(@".\case.txt");   
      string[] words = { "file", "sıfır", "Dženana" };
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 new CultureInfo("en-US"),  
                                 new CultureInfo("tr-TR") };

      foreach (var word in words) {
         sw.WriteLine("{0}:", word);
         foreach (var culture in cultures) {
            string name = String.IsNullOrEmpty(culture.Name) ? 
                                 "Invariant" : culture.Name;
            string upperWord = word.ToUpper(culture);
            sw.WriteLine("   {0,10}: {1,7} {2, 38}", name, 
                         upperWord, ShowHexValue(upperWord));
         }
         sw.WriteLine();  
      }
      sw.Close();
   }

   private static string ShowHexValue(string s)
   {
      string retval = null;
      foreach (var ch in s) {
         byte[] bytes = BitConverter.GetBytes(ch);
         retval += String.Format("{0:X2} {1:X2} ", bytes[1], bytes[0]);     
      }
      return retval;
   } 
}
// The example displays the following output:
//    file:
//        Invariant:    FILE               00 46 00 49 00 4C 00 45 
//            en-US:    FILE               00 46 00 49 00 4C 00 45 
//            tr-TR:    FİLE               00 46 01 30 00 4C 00 45 
//    
//    sıfır:
//        Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52 
//            en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52 
//            tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52 
//    
//    Dženana:
//        Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41 
//            en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
//            tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41
open System
open System.Globalization
open System.IO

let showHexValue (s: string) =
    let mutable retval = ""
    for ch in s do
        let bytes = BitConverter.GetBytes ch
        retval <- retval + String.Format("{0:X2} {1:X2} ", bytes[1], bytes[0])
    retval

do
    use sw = new StreamWriter(@".\case.txt")
    let words = [| "file"; "sıfır"; "Dženana" |]
    let cultures = 
        [| CultureInfo.InvariantCulture 
           CultureInfo "en-US"
           CultureInfo "tr-TR" |]

    for word in words do
        sw.WriteLine("{0}:", word)
        for culture in cultures do
            let name =
                 if String.IsNullOrEmpty culture.Name then "Invariant" else culture.Name
            let upperWord = word.ToUpper culture
            sw.WriteLine("   {0,10}: {1,7} {2, 38}", name, upperWord, showHexValue upperWord)
        sw.WriteLine()
    sw.Close()

// The example displays the following output:
//    file:
//        Invariant:    FILE               00 46 00 49 00 4C 00 45
//            en-US:    FILE               00 46 00 49 00 4C 00 45
//            tr-TR:    FİLE               00 46 01 30 00 4C 00 45
//
//    sıfır:
//        Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52
//            en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52
//            tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52
//
//    Dženana:
//        Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41
//            en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41
//            tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41
Imports System.Globalization
Imports System.IO

Module Example1
    Public Sub Main()
        Dim sw As New StreamWriter(".\case.txt")
        Dim words As String() = {"file", "sıfır", "Dženana"}
        Dim cultures() As CultureInfo = {CultureInfo.InvariantCulture,
                                        New CultureInfo("en-US"),
                                        New CultureInfo("tr-TR")}

        For Each word In words
            sw.WriteLine("{0}:", word)
            For Each culture In cultures
                Dim name As String = If(String.IsNullOrEmpty(culture.Name),
                                 "Invariant", culture.Name)
                Dim upperWord As String = word.ToUpper(culture)
                sw.WriteLine("   {0,10}: {1,7} {2, 38}", name,
                         upperWord, ShowHexValue(upperWord))

            Next
            sw.WriteLine()
        Next
        sw.Close()
    End Sub

    Private Function ShowHexValue(s As String) As String
        Dim retval As String = Nothing
        For Each ch In s
            Dim bytes() As Byte = BitConverter.GetBytes(ch)
            retval += String.Format("{0:X2} {1:X2} ", bytes(1), bytes(0))
        Next
        Return retval
    End Function
End Module
' The example displays the following output:
'    file:
'        Invariant:    FILE               00 46 00 49 00 4C 00 45 
'            en-US:    FILE               00 46 00 49 00 4C 00 45 
'            tr-TR:    FİLE               00 46 01 30 00 4C 00 45 
'    
'    sıfır:
'        Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52 
'            en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52 
'            tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52 
'    
'    Dženana:
'        Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41 
'            en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
'            tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41

剖析和格式化

格式化和剖析是反向作業。 格式化規則決定如何將日期和時間或數位等值轉換成其字串表示法,而剖析規則則決定如何將字串表示轉換成日期和時間等值。 格式和剖析規則都相依於文化慣例。 下列範例說明解譯特定文化特性日期字串時可能發生的模棱兩可。 若不知道用來產生日期字串的文化特性慣例,就無法知道 2011 年 3 月 1 日、3/1/2011 和 01/03/2011 是否代表 2011 年 1 月 3 日或 2011 年 3 月 1 日。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime date = new DateTime(2011, 3, 1);
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 new CultureInfo("en-US"), 
                                 new CultureInfo("fr-FR") };

      foreach (var culture in cultures)
         Console.WriteLine("{0,-12} {1}", String.IsNullOrEmpty(culture.Name) ?
                           "Invariant" : culture.Name, 
                           date.ToString("d", culture));                                    
   }
}
// The example displays the following output:
//       Invariant    03/01/2011
//       en-US        3/1/2011
//       fr-FR        01/03/2011
open System
open System.Globalization

let date = DateTime(2011, 3, 1)
let cultures = 
      [| CultureInfo.InvariantCulture
         CultureInfo "en-US"
         CultureInfo "fr-FR" |]

for culture in cultures do
    printfn $"""{(if String.IsNullOrEmpty culture.Name then "Invariant" else culture.Name),-12} {date.ToString("d", culture)}"""
// The example displays the following output:
//       Invariant    03/01/2011
//       en-US        3/1/2011
//       fr-FR        01/03/2011
Imports System.Globalization

Module Example8
    Public Sub Main()
        Dim dat As Date = #3/1/2011#
        Dim cultures() As CultureInfo = {CultureInfo.InvariantCulture,
                                        New CultureInfo("en-US"),
                                        New CultureInfo("fr-FR")}

        For Each culture In cultures
            Console.WriteLine("{0,-12} {1}", If(String.IsNullOrEmpty(culture.Name),
                           "Invariant", culture.Name),
                           dat.ToString("d", culture))
        Next
    End Sub
End Module
' The example displays the following output:
'       Invariant    03/01/2011
'       en-US        3/1/2011
'       fr-FR        01/03/2011

同樣地,如下列範例所示,單一字串可能會根據剖析作業中使用慣例的文化特性產生不同的日期。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString = "07/10/2011";
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 CultureInfo.CreateSpecificCulture("en-GB"), 
                                 CultureInfo.CreateSpecificCulture("en-US") };
      Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}\n", "Date String", "Culture", 
                                                 "Month", "Day");
      foreach (var culture in cultures) {
         DateTime date = DateTime.Parse(dateString, culture);
         Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString, 
                           String.IsNullOrEmpty(culture.Name) ?
                           "Invariant" : culture.Name, 
                           date.Month, date.Day);
      }                      
   }
}
// The example displays the following output:
//       Date String     Culture    Month      Day
//       
//       07/10/2011    Invariant        7       10
//       07/10/2011        en-GB       10        7
//       07/10/2011        en-US        7       10
open System
open System.Globalization

let dateString = "07/10/2011"
let cultures = 
    [| CultureInfo.InvariantCulture
       CultureInfo.CreateSpecificCulture "en-GB"
       CultureInfo.CreateSpecificCulture "en-US" |]
printfn $"""{"Date String",-12} {"Culture",10} {"Month",8} {"Day",8}\n"""
for culture in cultures do
    let date = DateTime.Parse(dateString, culture)
    printfn $"""{dateString,-12} {(if String.IsNullOrEmpty culture.Name then "Invariant" else culture.Name),10} {date.Month,8} {date.Day,8}"""
// The example displays the following output:
//       Date String     Culture    Month      Day
//
//       07/10/2011    Invariant        7       10
//       07/10/2011        en-GB       10        7
//       07/10/2011        en-US        7       10
Imports System.Globalization

Module Example18
    Public Sub Main()
        Dim dateString As String = "07/10/2011"
        Dim cultures() As CultureInfo = {CultureInfo.InvariantCulture,
                                        CultureInfo.CreateSpecificCulture("en-GB"),
                                        CultureInfo.CreateSpecificCulture("en-US")}
        Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", "Date String", "Culture",
                                                 "Month", "Day")
        Console.WriteLine()
        For Each culture In cultures
            Dim dat As Date = DateTime.Parse(dateString, culture)
            Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString,
                           If(String.IsNullOrEmpty(culture.Name),
                           "Invariant", culture.Name),
                           dat.Month, dat.Day)
        Next
    End Sub
End Module
' The example displays the following output:
'       Date String     Culture    Month      Day
'       
'       07/10/2011    Invariant        7       10
'       07/10/2011        en-GB       10        7
'       07/10/2011        en-US        7       10

字串比較和排序

比較和排序字串的慣例會因文化特性而異。 例如,排序順序可能以注音或字元的視覺表示為基礎。 在東亞語言中,文字是按照筆劃數和部首進行排序的。 排序也取決於字母順序使用的順序語言和文化特性。 例如,丹麥文的 "Æ" 字元在字母順序中排列在 "Z" 之後。 此外,比較可能會區分大小寫或不區分大小寫,且大小寫規則可能會因文化而異。 另一方面,序數比較會在比較和排序字串時,使用字元串中個別字元的 Unicode 字碼點。

排序規則會決定 Unicode 字元的字母順序,以及兩個字串彼此的比較方式。 例如, String.Compare(String, String, StringComparison) 方法會根據 StringComparison 參數比較兩個字串。 如果參數值為 StringComparison.CurrentCulture,則方法會執行使用目前文化特性慣例的語言比較;如果參數值為 StringComparison.Ordinal,則方法會執行序數比較。 因此,如下列範例所示,如果目前的文化特性是美式英文,則第一次呼叫 方法(使用區分文化特性的比較)會將 “a” 視為小於 “A”,但對相同方法的第二次呼叫 String.Compare(String, String, StringComparison) (使用序數比較)會將 “a” 視為大於 “A”。

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture));
      Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal));
   }
}
// The example displays the following output:
//       1
//       -32
open System
open System.Globalization
open System.Threading

Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"
printfn $"""{String.Compare("A", "a", StringComparison.CurrentCulture)}"""
printfn $"""{String.Compare("A", "a", StringComparison.Ordinal)}"""
// The example displays the following output:
//       1
//       -32
Imports System.Globalization
Imports System.Threading

Module Example3
    Public Sub Main()
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
        Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture))
        Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal))
    End Sub
End Module
' The example displays the following output:
'       1                                                                                     
'       -32

.NET 支援文字、字串和序數排序規則:

  • 文字排序會執行具文化敏感性的字串比較,其中某些非字母與數字的 Unicode 字元可能會被指派特定的權重。 例如,連字元(-)可能指派了非常小的權重,如此一來,「coop」和「co-op」會在排序列表中緊鄰出現。 如需使用文字排序規則比較兩個字串的方法清單String,請參閱依類別排序的字串作業一節。

  • 字串排序也會執行考慮文化差異的比較。 它類似於單字排序,不同之處在於沒有特殊情況,而且所有非字母數字符號都位於所有字母數字的 Unicode 字元之前。 藉由呼叫具有 CompareInfo.Compare 參數並傳遞值 optionsCompareOptions.StringSort 方法多載,即可使用字串排序規則來比較兩個字串。 請注意,這是 .NET 唯一使用字串排序規則比較兩個字符串的方法。

  • 序數排序會根據字串中每個 Char 物件的數值來比較字串。 序數比較會自動區分大小寫,因為小寫和大寫版本的字元具有不同的字碼點。 不過,如果案例不重要,您可以指定忽略大小寫的序數字比較。 這相當於使用不區別文化將字串轉換成大寫,然後對結果執行序數比較。 如需使用序數排序規則比較兩個字串的方法清單String,請參閱依類別排序的字串作業一節。

任何明確或隱含使用 CultureInfo 物件的比較,都是文化敏感性比較,包括由 CultureInfo.InvariantCulture 屬性指定的不因文化變異的文化。 隱含文化特性是目前的文化特性,由 Thread.CurrentCultureCultureInfo.CurrentCulture 屬性指定。 字母字元(即方法Char.IsLetter回傳true的字元)在不同文化中的排序順序存在相當大的差異。 透過提供 CultureInfo 物件給像是 Compare(String, String, CultureInfo, CompareOptions) 的字串比較方法,您可以指定依據特定文化區分的比較,從而使用該文化的習慣。 您可以指定一個使用目前文化特性慣例的文化敏感比較,方法是提供 StringComparison.CurrentCultureStringComparison.CurrentCultureIgnoreCaseCompareOptions 列舉中除 CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase 以外的任一成員,並將其傳遞給 Compare 方法的適當多載。 區分文化特性的比較通常適用於排序,而序數比較則不適用。 序數比較通常適用於判斷兩個字串是否相等(也就是判斷身分識別),而區分文化特性的比較則不適用。

下列範例說明區分文化特性和序數比較之間的差異。 此範例使用序數比較及丹麥 (da-DK) 和美國 (en-US) 文化特性的慣例來評估三個字串 "Apple"、"Æble" 和 "AEble"(在每次呼叫方法時,這兩種文化特性中的一種會設為預設文化特性)。 由於丹麥文會將 「Æ」 字元視為個別字母,並在字母表中將它排序為 “Z”,因此字串 “Æble” 大於 “Apple”。 不過,“Æble” 不被視為等於 “AEble”,因此 “Æble” 也大於 “AEble”。 en-US 文化特性不包含字母“Æ”,但將其視為相當於 “AE”,這解釋了為什麼 “Æble” 小於 “Apple”,但等於 “AEble”。 另一方面,序數比較會將 “Apple” 視為小於 “Æble”,而 “Æble” 則大於 “AEble”。

using System;
using System.Globalization;
using System.Threading;

public class CompareStringSample
{
   public static void Main()
   {
      string str1 = "Apple";
      string str2 = "Æble"; 
      string str3 = "AEble";
      
      // Set the current culture to Danish in Denmark.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2));
      Console.WriteLine("Comparison of {0} with {1}: {2}\n", 
                        str2, str3, String.Compare(str2, str3));
      
      // Set the current culture to English in the U.S.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2));
      Console.WriteLine("Comparison of {0} with {1}: {2}\n", 
                        str2, str3, String.Compare(str2, str3));
      
      // Perform an ordinal comparison.
      Console.WriteLine("Ordinal comparison");
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, 
                        String.Compare(str1, str2, StringComparison.Ordinal));
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str2, str3, 
                        String.Compare(str2, str3, StringComparison.Ordinal));
   }
}
// The example displays the following output:
//       Current culture: da-DK
//       Comparison of Apple with Æble: -1
//       Comparison of Æble with AEble: 1
//       
//       Current culture: en-US
//       Comparison of Apple with Æble: 1
//       Comparison of Æble with AEble: 0
//       
//       Ordinal comparison
//       Comparison of Apple with Æble: -133
//       Comparison of Æble with AEble: 133
open System
open System.Globalization
open System.Threading

let str1 = "Apple"
let str2 = "Æble"
let str3 = "AEble"

// Set the current culture to Danish in Denmark.
Thread.CurrentThread.CurrentCulture <- CultureInfo "da-DK"
printfn $"Current culture: {CultureInfo.CurrentCulture.Name}"
printfn $"Comparison of {str1} with {str2}: {String.Compare(str1, str2)}"
printfn $"Comparison of {str2} with {str3}: {String.Compare(str2, str3)}\n"

// Set the current culture to English in the U.S.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"Current culture: {CultureInfo.CurrentCulture.Name}"
printfn $"Comparison of {str1} with {str2}: {String.Compare(str1, str2)}"
printfn $"Comparison of {str2} with {str3}: {String.Compare(str2, str3)}\n"

// Perform an ordinal comparison.
printfn "Ordinal comparison"
printfn $"Comparison of {str1} with {str2}: {String.Compare(str1, str2, StringComparison.Ordinal)}"
printfn $"Comparison of {str2} with {str3}: {String.Compare(str2, str3, StringComparison.Ordinal)}"
// The example displays the following output:
//       Current culture: da-DK
//       Comparison of Apple with Æble: -1
//       Comparison of Æble with AEble: 1
//
//       Current culture: en-US
//       Comparison of Apple with Æble: 1
//       Comparison of Æble with AEble: 0
//
//       Ordinal comparison
//       Comparison of Apple with Æble: -133
//       Comparison of Æble with AEble: 133
Imports System.Globalization
Imports System.Threading

Public Module Example6
    Public Sub Main()
        Dim str1 As String = "Apple"
        Dim str2 As String = "Æble"
        Dim str3 As String = "AEble"

        ' Set the current culture to Danish in Denmark.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("da-DK")
        Console.WriteLine("Current culture: {0}",
                        CultureInfo.CurrentCulture.Name)
        Console.WriteLine("Comparison of {0} with {1}: {2}",
                        str1, str2, String.Compare(str1, str2))
        Console.WriteLine("Comparison of {0} with {1}: {2}",
                        str2, str3, String.Compare(str2, str3))
        Console.WriteLine()

        ' Set the current culture to English in the U.S.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("Current culture: {0}",
                        CultureInfo.CurrentCulture.Name)
        Console.WriteLine("Comparison of {0} with {1}: {2}",
                        str1, str2, String.Compare(str1, str2))
        Console.WriteLine("Comparison of {0} with {1}: {2}",
                        str2, str3, String.Compare(str2, str3))
        Console.WriteLine()

        ' Perform an ordinal comparison.
        Console.WriteLine("Ordinal comparison")
        Console.WriteLine("Comparison of {0} with {1}: {2}",
                        str1, str2,
                        String.Compare(str1, str2, StringComparison.Ordinal))
        Console.WriteLine("Comparison of {0} with {1}: {2}",
                        str2, str3,
                        String.Compare(str2, str3, StringComparison.Ordinal))
    End Sub
End Module
' The example displays the following output:
'       Current culture: da-DK
'       Comparison of Apple with Æble: -1
'       Comparison of Æble with AEble: 1
'       
'       Current culture: en-US
'       Comparison of Apple with Æble: 1
'       Comparison of Æble with AEble: 0
'       
'       Ordinal comparison
'       Comparison of Apple with Æble: -133
'       Comparison of Æble with AEble: 133

使用下列一般指導方針來選擇適當的排序或字串比較方法:

  • 如果您想要根據使用者的文化特性來排序字串,您應該根據目前文化特性的慣例來排序字串。 如果使用者的文化特性變更,排序字串的順序也會隨之變更。 例如,同義字應用程序應該一律根據使用者的文化特性來排序單字。

  • 如果您想要根據特定文化特性的慣例來排序字串,您應該藉由將代表該文化特性的物件提供給 CultureInfo 比較方法來排序它們。 例如,在設計來教導學生特定語言的應用程式中,您想要根據其中一種語言之文化特性的慣例來排序字串。

  • 如果您希望字串的順序在文化特性之間保持不變,您應該根據不因文化特性而異的慣例來排序字串,或使用序數比較。 例如,您會使用序數排序來組織檔名、進程、Mutex 或命名管道。

  • 如需涉及安全性決策的比較(例如判斷用戶名稱是否有效),您應該一律藉由呼叫 Equals 方法的重載來執行相等的序數測試。

Note

字串比較中使用的文化敏感排序與大小寫規則,取決於底層作業系統所支援的 Unicode 標準版本。

如需文字、字串和序數排序規則的詳細資訊,請參閱 System.Globalization.CompareOptions 主題。 如需何時使用每個規則的其他建議,請參閱 使用字串的最佳做法。

通常,您不會呼叫字串比較方法,例如 Compare 直接判斷字串的排序順序。 相反地,比較方法會藉由排序 方法呼叫,例如 Array.SortList<T>.Sort。 下列範例會執行四個不同的排序作業(使用當前文化特性的文字排序、使用非變異文化特性的文字排序、序數排序,及使用非變異文化特性的字串排序),且無需明確呼叫字串比較方法,不過它們確實指定了要使用的比較類型。 請注意,每種類型的排序都會在其陣列中產生唯一的字符串順序。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
 
public class Example
{
   public static void Main()
   {
      string[] strings = { "coop", "co-op", "cooperative", 
                           "co\u00ADoperative", "cœur", "coeur" };

      // Perform a word sort using the current (en-US) culture.
      string[] current = new string[strings.Length]; 
      strings.CopyTo(current, 0); 
      Array.Sort(current, StringComparer.CurrentCulture);

      // Perform a word sort using the invariant culture.
      string[] invariant = new string[strings.Length];
      strings.CopyTo(invariant, 0); 
      Array.Sort(invariant, StringComparer.InvariantCulture);

      // Perform an ordinal sort.
      string[] ordinal = new string[strings.Length];
      strings.CopyTo(ordinal, 0); 
      Array.Sort(ordinal, StringComparer.Ordinal);

      // Perform a string sort using the current culture.
      string[] stringSort = new string[strings.Length];
      strings.CopyTo(stringSort, 0); 
      Array.Sort(stringSort, new SCompare());

      // Display array values
      Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}\n", 
                        "Original", "Word Sort", "Invariant Word", 
                        "Ordinal Sort", "String Sort");
      for (int ctr = 0; ctr < strings.Length; ctr++)
         Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", 
                           strings[ctr], current[ctr], invariant[ctr], 
                           ordinal[ctr], stringSort[ctr] );          
   }
}

// IComparer<String> implementation to perform string sort.
internal class SCompare : IComparer<String>
{
   public int Compare(string x, string y)
   {
      return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort);
   }
}
// The example displays the following output:
//         Original     Word Sort  Invariant Word  Ordinal Sort   String Sort
//    
//             coop          cœur            cœur         co-op         co-op
//            co-op         coeur           coeur         coeur          cœur
//      cooperative          coop            coop          coop         coeur
//     co­operative         co-op           co-op   cooperative          coop
//             cœur   cooperative     cooperative  co­operative   cooperative
//            coeur  co­operative    co­operative          cœur  co­operative
open System
open System.Collections.Generic
open System.Globalization

// IComparer<String> implementation to perform string sort using an F# object expression.
let scompare = 
    { new IComparer<String> with
        member _.Compare(x, y) =
            CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort) }

let strings = [| "coop"; "co-op"; "cooperative"; "co\u00ADoperative"; "cœur"; "coeur" |]

// Perform a word sort using the current (en-US) culture.
let current = Array.copy strings
Array.Sort(current, StringComparer.CurrentCulture)

// Perform a word sort using the invariant culture.
let invariant = Array.copy strings
Array.Sort(invariant, StringComparer.InvariantCulture)

// Perform an ordinal sort.
let ordinal = Array.copy strings
Array.Sort(ordinal, StringComparer.Ordinal)

// Perform a string sort using the current culture.
let stringSort = Array.copy strings
Array.Sort(stringSort, scompare)

// Display array values
printfn "%13s %13s %15s %13s %13s\n" "Original" "Word Sort" "Invariant Word" "Ordinal Sort" "String Sort"
for i = 0 to strings.Length - 1 do
    printfn "%13s %13s %15s %13s %13s\n" strings[i] current[i] invariant[i] ordinal[i] stringSort[i]

// The example displays the following output:
//         Original     Word Sort  Invariant Word  Ordinal Sort   String Sort
//
//             coop          cœur            cœur         co-op         co-op
//            co-op         coeur           coeur         coeur          cœur
//      cooperative          coop            coop          coop         coeur
//     co­operative         co-op           co-op   cooperative          coop
//             cœur   cooperative     cooperative  co­operative   cooperative
//            coeur  co­operative    co­operative          cœur  co­operative
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization

Module Example4
    Public Sub Main()
        Dim strings() As String = {"coop", "co-op", "cooperative",
                                  "co" + ChrW(&HAD) + "operative",
                                  "cœur", "coeur"}

        ' Perform a word sort using the current (en-US) culture.
        Dim current(strings.Length - 1) As String
        strings.CopyTo(current, 0)
        Array.Sort(current, StringComparer.CurrentCulture)

        ' Perform a word sort using the invariant culture.
        Dim invariant(strings.Length - 1) As String
        strings.CopyTo(invariant, 0)
        Array.Sort(invariant, StringComparer.InvariantCulture)

        ' Perform an ordinal sort.
        Dim ordinal(strings.Length - 1) As String
        strings.CopyTo(ordinal, 0)
        Array.Sort(ordinal, StringComparer.Ordinal)

        ' Perform a string sort using the current culture.
        Dim stringSort(strings.Length - 1) As String
        strings.CopyTo(stringSort, 0)
        Array.Sort(stringSort, New SCompare())

        ' Display array values
        Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}",
                        "Original", "Word Sort", "Invariant Word",
                        "Ordinal Sort", "String Sort")
        Console.WriteLine()

        For ctr As Integer = 0 To strings.Length - 1
            Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}",
                           strings(ctr), current(ctr), invariant(ctr),
                           ordinal(ctr), stringSort(ctr))
        Next
    End Sub
End Module

' IComparer<String> implementation to perform string sort.
Friend Class SCompare : Implements IComparer(Of String)
   Public Function Compare(x As String, y As String) As Integer _
                   Implements IComparer(Of String).Compare
      Return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort)
   End Function
End Class
' The example displays the following output:
'         Original     Word Sort  Invariant Word  Ordinal Sort   String Sort
'    
'             coop          cœur            cœur         co-op         co-op
'            co-op         coeur           coeur         coeur          cœur
'      cooperative          coop            coop          coop         coeur
'     co­operative         co-op           co-op   cooperative          coop
'             cœur   cooperative     cooperative  co­operative   cooperative
'            coeur  co­operative    co­operative          cœur  co­operative

Tip

在內部,.NET 會使用排序索引鍵來支援文化特性敏感的字元串比較。 字串中的每個字元都有數個分類的排序權數,包括字母、大小寫和變音符號。 類別所代表的 SortKey 排序索引鍵會針對特定字串提供這些權數的存放庫。 如果您的應用程式在同一組字串上執行大量搜尋或排序作業,您可以針對它使用的所有字串產生和儲存排序索引鍵,以改善其效能。 當需要排序或比較作業時,您可以使用排序索引鍵,而不是字串。 如需詳細資訊,請參閱 SortKey 類別。

如果您未指定字串比較慣例,排序方法(例如 Array.Sort(Array))會在字串上執行依文化敏感且區分大小寫的排序。 下列範例說明變更目前的文化設定如何影響在陣列中排序字串的順序。 它會建立三個字串的陣列。 首先,它會將 System.Threading.Thread.CurrentThread.CurrentCulture 屬性設定為 en-US,並呼叫 Array.Sort(Array) 方法。 產生的排序順序是以英文 (美國) 文化特性的排序慣例為基礎。 接下來,此範例會將 System.Threading.Thread.CurrentThread.CurrentCulture 屬性設定為da-DK,並再次呼叫 Array.Sort 方法。 請注意,產生的排序順序與 en-US 結果有何不同,因為它使用丹麥文(丹麥)的排序慣例。

using System;
using System.Globalization;
using System.Threading;

public class ArraySort
{
   public static void Main(String[] args)
   {
      // Create and initialize a new array to store the strings.
      string[] stringArray = { "Apple", "Æble", "Zebra"};

      // Display the values of the array.
      Console.WriteLine( "The original string array:");
      PrintIndexAndValues(stringArray);

      // Set the CurrentCulture to "en-US".
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      // Sort the values of the array.
      Array.Sort(stringArray);

      // Display the values of the array.
      Console.WriteLine("After sorting for the culture \"en-US\":");
      PrintIndexAndValues(stringArray);

      // Set the CurrentCulture to "da-DK".
      Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
      // Sort the values of the Array.
      Array.Sort(stringArray);

      // Display the values of the array.
      Console.WriteLine("After sorting for the culture \"da-DK\":");
      PrintIndexAndValues(stringArray);
   }
   public static void PrintIndexAndValues(string[] myArray)
   {
      for (int i = myArray.GetLowerBound(0); i <=
            myArray.GetUpperBound(0); i++ )
         Console.WriteLine("[{0}]: {1}", i, myArray[i]);
      Console.WriteLine();
   }
}
// The example displays the following output:
//       The original string array:
//       [0]: Apple
//       [1]: Æble
//       [2]: Zebra
//
//       After sorting for the "en-US" culture:
//       [0]: Æble
//       [1]: Apple
//       [2]: Zebra
//
//       After sorting for the culture "da-DK":
//       [0]: Apple
//       [1]: Zebra
//       [2]: Æble
open System
open System.Globalization
open System.Threading

let printIndexAndValues (myArray: string[]) =
    for i = myArray.GetLowerBound 0 to myArray.GetUpperBound 0 do
        printfn $"[{i}]: {myArray[i]}" 
    printfn ""

// Create and initialize a new array to store the strings.
let stringArray = [| "Apple"; "Æble"; "Zebra" |]

// Display the values of the array.
printfn "The original string array:"
printIndexAndValues stringArray

// Set the CurrentCulture to "en-US".
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
// Sort the values of the array.
Array.Sort stringArray

// Display the values of the array.
printfn "After sorting for the culture \"en-US\":"
printIndexAndValues stringArray

// Set the CurrentCulture to "da-DK".
Thread.CurrentThread.CurrentCulture <- CultureInfo "da-DK"
// Sort the values of the Array.
Array.Sort stringArray

// Display the values of the array.
printfn "After sorting for the culture \"da-DK\":"
printIndexAndValues stringArray
// The example displays the following output:
//       The original string array:
//       [0]: Apple
//       [1]: Æble
//       [2]: Zebra
//
//       After sorting for the "en-US" culture:
//       [0]: Æble
//       [1]: Apple
//       [2]: Zebra
//
//       After sorting for the culture "da-DK":
//       [0]: Apple
//       [1]: Zebra
//       [2]: Æble
Imports System.Globalization
Imports System.IO
Imports System.Threading

Public Class TextToFile   
   Public Shared Sub Main()
      ' Creates and initializes a new array to store 
      ' these date/time objects.
      Dim stringArray() As String = { "Apple", "Æble", "Zebra"}
      
      ' Displays the values of the array.
      Console.WriteLine("The original string array:")
      PrintIndexAndValues(stringArray)
      
      ' Set the CurrentCulture to "en-US".
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      ' Sort the values of the Array.
      Array.Sort(stringArray)
      
      ' Display the values of the array.
      Console.WriteLine("After sorting for the ""en-US"" culture:")
      PrintIndexAndValues(stringArray)
      
      ' Set the CurrentCulture to "da-DK".
      Thread.CurrentThread.CurrentCulture = New CultureInfo("da-DK")
      ' Sort the values of the Array.
      Array.Sort(stringArray)
      
      ' Displays the values of the Array.
      Console.WriteLine("After sorting for the culture ""da-DK"":")
      PrintIndexAndValues(stringArray)
   End Sub

   Public Shared Sub PrintIndexAndValues(myArray() As String)
      For i As Integer = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
         Console.WriteLine("[{0}]: {1}", i, myArray(i))
      Next
      Console.WriteLine()
   End Sub 
End Class
' The example displays the following output:
'       The original string array:
'       [0]: Apple
'       [1]: Æble
'       [2]: Zebra
'       
'       After sorting for the "en-US" culture:
'       [0]: Æble
'       [1]: Apple
'       [2]: Zebra
'       
'       After sorting for the culture "da-DK":
'       [0]: Apple
'       [1]: Zebra
'       [2]: Æble

Warning

如果比較字串的主要目的是判斷字串是否相等,您應該呼叫 String.Equals 方法。 一般而言,您應該使用 Equals 來執行序數比較。 方法 String.Compare 主要是為了排序字串。

字串搜尋的方法,例如 String.StartsWithString.IndexOf,也可以執行考慮文化差異或序數的字串比較。 下列範例說明使用 IndexOf 方法進行序數與區分文化特性的比較之間的差異。 考慮文化差異的搜尋中,當目前的文化設定為英文(美國)時,會將子字串 “oe” 視為與合字 “œ” 相匹配。 因為軟連字元(U+00AD)是零寬度字元,因此在搜尋時將其視為相當於String.Empty,並在字串開頭找到匹配的結果。 另一方面,序列搜尋在任何情況下都找不到匹配。

using System;

public class Example
{
   public static void Main()
   {
      // Search for "oe" and "œu" in "œufs" and "oeufs".
      string s1 = "œufs";
      string s2 = "oeufs";
      FindInString(s1, "oe", StringComparison.CurrentCulture);
      FindInString(s1, "oe", StringComparison.Ordinal);
      FindInString(s2, "œu", StringComparison.CurrentCulture);
      FindInString(s2, "œu", StringComparison.Ordinal);
      Console.WriteLine();
      
      string s3 = "co\u00ADoperative";
      FindInString(s3, "\u00AD", StringComparison.CurrentCulture);
      FindInString(s3, "\u00AD", StringComparison.Ordinal);
   }

   private static void FindInString(string s, string substring, StringComparison options)
   {
      int result = s.IndexOf(substring, options);
      if (result != -1)
         Console.WriteLine("'{0}' found in {1} at position {2}", 
                           substring, s, result);
      else
         Console.WriteLine("'{0}' not found in {1}", 
                           substring, s);                                                  
   }
}
// The example displays the following output:
//       'oe' found in œufs at position 0
//       'oe' not found in œufs
//       'œu' found in oeufs at position 0
//       'œu' not found in oeufs
//       
//       '­' found in co­operative at position 0
//       '­' found in co­operative at position 2
open System

let findInString (s: string) (substring: string) (options: StringComparison) =
    let result = s.IndexOf(substring, options)
    if result <> -1 then
        printfn $"'{substring}' found in {s} at position {result}"
    else
        printfn $"'{substring}' not found in {s}"

// Search for "oe" and "œu" in "œufs" and "oeufs".
let s1 = "œufs"
let s2 = "oeufs"
findInString s1 "oe" StringComparison.CurrentCulture
findInString s1 "oe" StringComparison.Ordinal
findInString s2 "œu" StringComparison.CurrentCulture
findInString s2 "œu" StringComparison.Ordinal
printfn ""

let s3 = "co\u00ADoperative"
findInString s3 "\u00AD" StringComparison.CurrentCulture
findInString s3 "\u00AD" StringComparison.Ordinal

// The example displays the following output:
//       'oe' found in œufs at position 0
//       'oe' not found in œufs
//       'œu' found in oeufs at position 0
//       'œu' not found in oeufs
//
//       '­' found in co­operative at position 0
//       '­' found in co­operative at position 2
Module Example5
    Public Sub Main()
        ' Search for "oe" and "œu" in "œufs" and "oeufs".
        Dim s1 As String = "œufs"
        Dim s2 As String = "oeufs"
        FindInString(s1, "oe", StringComparison.CurrentCulture)
        FindInString(s1, "oe", StringComparison.Ordinal)
        FindInString(s2, "œu", StringComparison.CurrentCulture)
        FindInString(s2, "œu", StringComparison.Ordinal)
        Console.WriteLine()

        Dim softHyphen As String = ChrW(&HAD)
        Dim s3 As String = "co" + softHyphen + "operative"
        FindInString(s3, softHyphen, StringComparison.CurrentCulture)
        FindInString(s3, softHyphen, StringComparison.Ordinal)
    End Sub

    Private Sub FindInString(s As String, substring As String,
                            options As StringComparison)
        Dim result As Integer = s.IndexOf(substring, options)
        If result <> -1 Then
            Console.WriteLine("'{0}' found in {1} at position {2}",
                           substring, s, result)
        Else
            Console.WriteLine("'{0}' not found in {1}",
                           substring, s)
        End If
    End Sub
End Module
' The example displays the following output:
'       'oe' found in œufs at position 0
'       'oe' not found in œufs
'       'œu' found in oeufs at position 0
'       'œu' not found in oeufs
'       
'       '­' found in co­operative at position 0
'       '­' found in co­operative at position 2

在字串中搜尋

字串搜尋方法,例如 String.StartsWithString.IndexOf,也可以執行考量文化特性的比較或序數字串比較,以判定指定字串中是否包含字元或子字串。

類別中 String 搜尋個別字元的搜尋方法,例如 IndexOf 方法或其中一組字元,例如 IndexOfAny 方法,都會執行序數搜尋。 若要對字元執行區分文化特性的搜尋,您必須呼叫 CompareInfo 或 之類的CompareInfo.IndexOf(String, Char)CompareInfo.LastIndexOf(String, Char)方法。 請注意,使用序數和區分文化特性的比較來搜尋字元的結果可能非常不同。 例如,搜尋預組合的 Unicode 字元,例如合字 “Æ” (U+00C6)可能會符合其元件以正確序列出現的情況,例如 “AE” (U+0041U+0045),這可能依文化差異而異。 下列範例說明搜尋個別字元時, String.IndexOf(Char)CompareInfo.IndexOf(String, Char) 方法之間的差異。 在使用 en-US 文化慣例時,字串 "aerial" 會出現合字 "æ" (U+00E6),但在使用 da-DK 文化慣例或進行序數比較時則不會出現。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      String[] cultureNames = { "da-DK", "en-US" };
      CompareInfo ci;
      String str = "aerial";
      Char ch = 'æ';  // U+00E6
      
      Console.Write("Ordinal comparison -- ");
      Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                        str.IndexOf(ch));
      
      foreach (var cultureName in cultureNames) {
         ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo;
         Console.Write("{0} cultural comparison -- ", cultureName);
         Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                           ci.IndexOf(str, ch));
      }
   }
}
// The example displays the following output:
//       Ordinal comparison -- Position of 'æ' in aerial: -1
//       da-DK cultural comparison -- Position of 'æ' in aerial: -1
//       en-US cultural comparison -- Position of 'æ' in aerial: 0
open System.Globalization

let cultureNames = [| "da-DK"; "en-US" |]
let str = "aerial"
let ch = 'æ'  // U+00E6

printf "Ordinal comparison -- "
printfn $"Position of '{ch}' in {str}: {str.IndexOf ch}"
                  
for cultureName in cultureNames do
    let ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo
    printf $"{cultureName} cultural comparison -- "
    printfn $"Position of '{ch}' in {str}: {ci.IndexOf(str, ch)}"
// The example displays the following output:
//       Ordinal comparison -- Position of 'æ' in aerial: -1
//       da-DK cultural comparison -- Position of 'æ' in aerial: -1
//       en-US cultural comparison -- Position of 'æ' in aerial: 0
Imports System.Globalization

Module Example19
    Public Sub Main()
        Dim cultureNames() As String = {"da-DK", "en-US"}
        Dim ci As CompareInfo
        Dim str As String = "aerial"
        Dim ch As Char = "æ"c  ' U+00E6

        Console.Write("Ordinal comparison -- ")
        Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                        str.IndexOf(ch))

        For Each cultureName In cultureNames
            ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo
            Console.Write("{0} cultural comparison -- ", cultureName)
            Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                           ci.IndexOf(str, ch))
        Next
    End Sub
End Module
' The example displays the following output:
'       Ordinal comparison -- Position of 'æ' in aerial: -1
'       da-DK cultural comparison -- Position of 'æ' in aerial: -1
'       en-US cultural comparison -- Position of 'æ' in aerial: 0

另一方面, String 搜尋字串而非字元的類別方法會執行區分文化特性的搜尋,如果未由 類型的 StringComparison參數明確指定搜尋選項。 唯一的例外狀況是 Contains,它會執行序數搜尋。

進行相等性測試

String.Compare使用 方法來判斷排序順序中兩個字串的關聯性。 通常,這是一項對文化敏感的操作。 相反地,呼叫 String.Equals 方法來測試是否相等。 由於相等測試通常會比較使用者輸入與某些已知字串,例如有效的使用者名稱、密碼或文件系統路徑,所以通常是序數運算。

Warning

可以呼叫 String.Compare 方法,並判斷傳回值是否為零,以測試是否相等。 不過,不建議使用這種做法。 若要判斷兩個字串是否相等,您應該呼叫 String.Equals 方法的某個多載版本。 要呼叫的慣用多載是實例 Equals(String, StringComparison) 方法或靜態 Equals(String, String, StringComparison) 方法,因為兩種方法都包含 System.StringComparison 明確指定比較類型的參數。

下列範例說明執行文化敏感性相等比較而非使用序數比較的危險。 在此情況下,程式碼的目的是要禁止從開頭為 “FILE://” 或 “file://” 的 URL 存取文件系統,方法是執行不區分大小寫的 URL 開頭與字串 “FILE://” 的比較。 不過,如果在開頭為「file://」的 URL 上使用土耳其文化特性進行比較,則相等性比較會失敗,因為在土耳其文中小寫「i」的大寫形式是「İ」,而不是「I」。 因此,無意中允許了文件系統存取。 另一方面,如果進行順序比較,則判斷相等的比較會成功,並且系統會拒絕對檔案系統的存取。

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");      

      string filePath = "file://c:/notes.txt";
      
      Console.WriteLine("Culture-sensitive test for equality:");
      if (!TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase))
         Console.WriteLine("Access to {0} is allowed.", filePath);
      else
         Console.WriteLine("Access to {0} is not allowed.", filePath);
      
      Console.WriteLine("\nOrdinal test for equality:");
      if (!TestForEquality(filePath, StringComparison.OrdinalIgnoreCase))
         Console.WriteLine("Access to {0} is allowed.", filePath);
      else
         Console.WriteLine("Access to {0} is not allowed.", filePath);
   }

   private static bool TestForEquality(string str, StringComparison cmp)
   {
      int position = str.IndexOf("://");
      if (position < 0) return false;

      string substring = str.Substring(0, position);  
      return substring.Equals("FILE", cmp);
   }
}
// The example displays the following output:
//       Culture-sensitive test for equality:
//       Access to file://c:/notes.txt is allowed.
//       
//       Ordinal test for equality:
//       Access to file://c:/notes.txt is not allowed.
open System
open System.Globalization
open System.Threading

let testForEquality (str: string) (cmp: StringComparison) =
    let position = str.IndexOf "://"
    if position < 0 then false
    else
        let substring = str.Substring(0, position)
        substring.Equals("FILE", cmp)

Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "tr-TR"

let filePath = "file://c:/notes.txt"

printfn "Culture-sensitive test for equality:"
if not (testForEquality filePath StringComparison.CurrentCultureIgnoreCase) then
    printfn $"Access to {filePath} is allowed."
else
    printfn $"Access to {filePath} is not allowed."

printfn "\nOrdinal test for equality:"
if not (testForEquality filePath StringComparison.OrdinalIgnoreCase) then
    printfn $"Access to {filePath} is allowed."
else
    printfn $"Access to {filePath} is not allowed."

// The example displays the following output:
//       Culture-sensitive test for equality:
//       Access to file://c:/notes.txt is allowed.
//
//       Ordinal test for equality:
//       Access to file://c:/notes.txt is not allowed.
Imports System.Globalization
Imports System.Threading

Module Example7
    Public Sub Main()
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR")

        Dim filePath As String = "file://c:/notes.txt"

        Console.WriteLine("Culture-sensitive test for equality:")
        If Not TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase) Then
            Console.WriteLine("Access to {0} is allowed.", filePath)
        Else
            Console.WriteLine("Access to {0} is not allowed.", filePath)
        End If
        Console.WriteLine()

        Console.WriteLine("Ordinal test for equality:")
        If Not TestForEquality(filePath, StringComparison.OrdinalIgnoreCase) Then
            Console.WriteLine("Access to {0} is allowed.", filePath)
        Else
            Console.WriteLine("Access to {0} is not allowed.", filePath)
        End If
    End Sub

    Private Function TestForEquality(str As String, cmp As StringComparison) As Boolean
        Dim position As Integer = str.IndexOf("://")
        If position < 0 Then Return False

        Dim substring As String = str.Substring(0, position)
        Return substring.Equals("FILE", cmp)
    End Function
End Module
' The example displays the following output:
'       Culture-sensitive test for equality:
'       Access to file://c:/notes.txt is allowed.
'       
'       Ordinal test for equality:
'       Access to file://c:/notes.txt is not allowed.

正規化

某些 Unicode 字元有多個表示法。 例如,下列任何一個代碼點都可以代表字母 「ắ」:

  • U+1EAF
  • U+0103 U+0301
  • U+0061 U+0306 U+0301

單一字元的多個表示法會使搜尋、排序、比對和其他字串作業複雜化。

Unicode 標準會定義稱為正規化的進程,針對任何對等二進位表示法傳回 Unicode 字元的一個二進位表示法。 正規化可以使用數種演算法,稱為正規化形式,遵循不同的規則。 .NET 支援 Unicode 正規化形式 C、D、KC 和 KD。 當字串正規化為相同的正規化形式時,可以使用序數比較加以比較。

序數比較是每個字串中對應 Char 物件之 Unicode 純量值的二進位比較。 類別 String 包含一些可以執行序數比較的方法,包括下列各項:

您可以藉由呼叫 String.IsNormalized() 方法來判斷字串是否正規化為正規化形式 C,或者您可以呼叫 String.IsNormalized(NormalizationForm) 方法,以判斷字串是否正規化為指定的正規化形式。 您也可以呼叫 String.Normalize() 方法,將字串轉換成正規化表單 C,也可以呼叫 String.Normalize(NormalizationForm) 方法,將字串轉換成指定的正規化表單。 如需正規化和比較字串的逐步資訊,請參閱 Normalize()Normalize(NormalizationForm) 方法。

下列簡單範例說明字串正規化。 它會在三個不同的字串中以三種不同的方式定義字母 「ố」,並使用序數比較來判斷每個字串與其他兩個字串不同。 接著,它會將每個字串轉換成支援的正規化形式,然後再次以指定的正規化形式執行每個字串的序數比較。 在每個案例中,第二個相等測試會顯示字串相等。

using System;
using System.Globalization;
using System.IO;
using System.Text;

public class Example
{
   private static StreamWriter sw;
   
   public static void Main()
   {
      sw = new StreamWriter(@".\TestNorm1.txt");

      // Define three versions of the same word. 
      string s1 = "sống";        // create word with U+1ED1
      string s2 = "s\u00F4\u0301ng";
      string s3 = "so\u0302\u0301ng";

      TestForEquality(s1, s2, s3);      
      sw.WriteLine();

      // Normalize and compare strings using each normalization form.
      foreach (string formName in Enum.GetNames(typeof(NormalizationForm)))
      {
         sw.WriteLine("Normalization {0}:\n", formName); 
         NormalizationForm nf = (NormalizationForm) Enum.Parse(typeof(NormalizationForm), formName);
         string[] sn = NormalizeStrings(nf, s1, s2, s3);
         TestForEquality(sn);           
         sw.WriteLine("\n");                                        
      }
      
      sw.Close();   
   }

   private static void TestForEquality(params string[] words)
   {
      for (int ctr = 0; ctr <= words.Length - 2; ctr++)
         for (int ctr2 = ctr + 1; ctr2 <= words.Length - 1; ctr2++) 
            sw.WriteLine("{0} ({1}) = {2} ({3}): {4}", 
                         words[ctr], ShowBytes(words[ctr]),
                         words[ctr2], ShowBytes(words[ctr2]),
                         words[ctr].Equals(words[ctr2], StringComparison.Ordinal));
   }

   private static string ShowBytes(string str)
   {
      string result = null;
      foreach (var ch in str)
         result += $"{(ushort)ch:X4} ";
      return result.Trim();            
   } 
   
   private static string[] NormalizeStrings(NormalizationForm nf, params string[] words)
   {
      for (int ctr = 0; ctr < words.Length; ctr++)
         if (!words[ctr].IsNormalized(nf))
            words[ctr] = words[ctr].Normalize(nf); 
      return words;   
   }
}
// The example displays the following output:
//       sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False
//       sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
//       sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
//       
//       Normalization FormC:
//       
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       
//       
//       Normalization FormD:
//       
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       
//       
//       Normalization FormKC:
//       
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       
//       
//       Normalization FormKD:
//       
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
open System
open System.IO
open System.Text

do
    use sw = new StreamWriter(@".\TestNorm1.txt")

    let showBytes (str: string) =
        let mutable result = ""
        for ch in str do
            result <- result + $"{uint16 ch:X4} "
        result.Trim()
    
    let testForEquality (words: string[]) =
        for ctr = 0 to words.Length - 2 do
            for ctr2 = ctr + 1 to words.Length - 1 do
                sw.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                            words[ctr], showBytes(words[ctr]),
                            words[ctr2], showBytes(words[ctr2]),
                            words[ctr].Equals(words[ctr2], StringComparison.Ordinal))

    let normalizeStrings nf (words: string[]) =
        for i = 0 to words.Length - 1 do
            if not (words[i].IsNormalized nf) then
                words[i] <- words[i].Normalize nf
        words

    // Define three versions of the same word.
    let s1 = "sống"        // create word with U+1ED1
    let s2 = "s\u00F4\u0301ng"
    let s3 = "so\u0302\u0301ng"

    testForEquality [| s1; s2; s3 |]
    sw.WriteLine()

    // Normalize and compare strings using each normalization form.
    for formName in Enum.GetNames typeof<NormalizationForm> do
        sw.WriteLine("Normalization {0}:\n", formName)
        let nf = Enum.Parse(typeof<NormalizationForm>, formName) :?> NormalizationForm
        let sn = normalizeStrings nf [| s1; s2; s3|]
        testForEquality sn
        sw.WriteLine "\n"

// The example displays the following output:
//       sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False
//       sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
//       sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
//
//       Normalization FormC:
//
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//
//
//       Normalization FormD:
//
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//
//
//       Normalization FormKC:
//
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//
//
//       Normalization FormKD:
//
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
Imports System.Globalization
Imports System.IO
Imports System.Text

Module Example16
    Private sw As StreamWriter

    Public Sub Main()
        sw = New StreamWriter(".\TestNorm1.txt")

        ' Define three versions of the same word. 
        Dim s1 As String = "sống"        ' create word with U+1ED1
        Dim s2 As String = "s" + ChrW(&HF4) + ChrW(&H301) + "ng"
        Dim s3 As String = "so" + ChrW(&H302) + ChrW(&H301) + "ng"

        TestForEquality(s1, s2, s3)
        sw.WriteLine()

        ' Normalize and compare strings using each normalization form.
        For Each formName In [Enum].GetNames(GetType(NormalizationForm))
            sw.WriteLine("Normalization {0}:", formName)
            Dim nf As NormalizationForm = CType([Enum].Parse(GetType(NormalizationForm), formName),
                                             NormalizationForm)
            Dim sn() As String = NormalizeStrings(nf, s1, s2, s3)
            TestForEquality(sn)
            sw.WriteLine(vbCrLf)
        Next

        sw.Close()
    End Sub

    Private Sub TestForEquality(ParamArray words As String())
        For ctr As Integer = 0 To words.Length - 2
            For ctr2 As Integer = ctr + 1 To words.Length - 1
                sw.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                         words(ctr), ShowBytes(words(ctr)),
                         words(ctr2), ShowBytes(words(ctr2)),
                         words(ctr).Equals(words(ctr2), StringComparison.Ordinal))
            Next
        Next
    End Sub

    Private Function ShowBytes(str As String) As String
        Dim result As String = Nothing
        For Each ch In str
            result += String.Format("{0} ", Convert.ToUInt16(ch).ToString("X4"))
        Next
        Return result.Trim()
    End Function

    Private Function NormalizeStrings(nf As NormalizationForm, ParamArray words() As String) As String()
        For ctr As Integer = 0 To words.Length - 1
            If Not words(ctr).IsNormalized(nf) Then
                words(ctr) = words(ctr).Normalize(nf)
            End If
        Next
        Return words
    End Function
End Module
' The example displays the following output:
'       sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False
'       sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
'       sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
'       
'       Normalization FormC:
'       
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       
'       
'       Normalization FormD:
'       
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       
'       
'       Normalization FormKC:
'       
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       
'       
'       Normalization FormKD:
'       
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True

如需正規化和正規化表單的詳細資訊,請參閱 System.Text.NormalizationFormunicode.org 網站上的 Unicode 標準附錄 #15:Unicode 正規化表單正規化常見問題

按類別分類的字串操作

類別 String 提供成員來比較字串、測試字串是否相等、尋找字串中的字元或子字串、修改字串、從字串擷取子字串、結合字串、格式化值、複製字元串,以及正規化字串。

比較字串

您可以使用下列 String 方法來比較字串,以在排序順序中判斷其相對位置:

  • Compare 會傳回整數,這個整數表示一個字元串與排序順序中的第二個字元串的關聯性。

  • CompareOrdinal 會傳回一個整數,這個整數表示一個字串與第二個字串的關聯性,根據其碼位的比較。

  • CompareTo 會傳回整數,這個整數表示目前字串實例與排序順序中的第二個字元串的關聯性。 CompareTo(String)方法為IComparable類別提供IComparable<T>String的實作。

測試字串是否相等

您可以呼叫 Equals 方法來判斷兩個字串是否相等。 實例 Equals(String, String, StringComparison) 和靜態 Equals(String, StringComparison) 多載可讓您指定比較是否區分文化特性或序數,以及是否考慮或忽略大小寫。 大部分的相等測試都是序數,而相等比較決定系統資源的存取權(例如文件系統物件)應該一律為序數。

尋找字串中的字元

類別 String 包含兩種搜尋方法:

Warning

如果您想要搜尋特定模式的字串,而不是特定子字串,您應該使用正則表達式。 如需詳細資訊,請參閱 .NET 正則表示式

修改字串

類別 String 包含下列方法,這些方法似乎修改字串的值:

  • Insert 將字串插入目前 String 實例中。

  • PadLeft 在字串開頭插入一或多個指定的字元。

  • PadRight 在字串結尾插入一或多個指定的字元。

  • Remove 會從目前 String 實例刪除子字串。

  • Replace 以目前 String 實例中的另一個子字串取代子字串。

  • ToLower 並將 ToLowerInvariant 字串中的所有字元轉換成小寫。

  • ToUpper 並將 ToUpperInvariant 字串中的所有字元轉換成大寫。

  • Trim 會從字串的開頭和結尾移除所有出現的字元。

  • TrimEnd 會從字串結尾移除所有出現的字元。

  • TrimStart 會從字串開頭移除所有出現的字元。

Important

所有字串修改方法都會傳回新的 String 物件。 它們不會修改目前實例的值。

從字串擷取子字串

方法會將 String.Split 單一字串分隔成多個字元串。 方法的多載可讓您指定多個分隔符、限制方法擷取的子字串數目、從子字串修剪空格符,以及指定傳回的字串中是否包含空字串(在分隔符相鄰時發生)。

合併字串

下列 String 方法可用於字串串連:

  • Concat 將一個或多個子字串結合成單一字串。
  • Join 將一個或多個子字串串連成單一元素,並在每個子字串之間加入分隔符。

格式化值

使用 String.Format 方法時,會利用複合格式功能,將字串中的一個或多個佔位元替換為某些物件或值的字串表示形式。 方法 Format 通常用來執行下列動作:

  • 在字串中嵌入數值的字串表示。
  • 在字串中嵌入日期和時間值的字串表示法。
  • 將列舉值的字串形式嵌入字串中。
  • 若要內嵌某些支援 IFormattable 字串中介面之物件的字串表示。
  • 以右對齊或靠左對齊較大字串內欄位中的子字串。

如需格式化作業和範例的詳細資訊,請參閱 Format 多載摘要。

編輯字串

您可以呼叫下列 String 方法來建立字串的複本:

  • Clone 傳回現有 String 對象的參考。
  • CopyTo 將字串的一部分複製到字元陣列。

正規化字串

在 Unicode 中,單一字元可以有多個字碼點。 正規化會將這些對等字元轉換成相同的二進位表示法。 String.Normalize方法會執行正規化,而 String.IsNormalized 方法會判斷字串是否正規化。

如需詳細資訊和範例,請參閱本文稍早的 標準化 一節。

建構函式

名稱 Description
String(Char, Int32)

將類別的新實例 String 初始化為指定的 Unicode 字元所指示的值,重複指定次數。

String(Char[], Int32, Int32)

將類別的新實例 String 初始化為由 Unicode 字元陣列、該陣列中的起始字元位置及長度所指示的值。

String(Char[])

將類別的新實例 String 初始化為指定字元陣列中所指示的 Unicode 字元。

String(Char*, Int32, Int32)

初始化一個新的類別實例 String ,初始化為指定指標指向 Unicode 字元陣列的值、該陣列中的起始字元位置及長度。

String(Char*)

將類別的新實例 String 初始化為指定指標指向 Unicode 字元陣列所指示的值。

String(ReadOnlySpan<Char>)

將該類別的新實例 String 初始化為指定唯讀區間內所指示的 Unicode 字元。

String(SByte*, Int32, Int32, Encoding)

初始化該類別的新實例 String ,初始化為指定指標指向一個 8 位元帶號整數陣列的值、該陣列中的起始位置、長度及一個 Encoding 物件。

String(SByte*, Int32, Int32)

初始化該類別的新實例 String 為指定指標指向一個 8 位元有符號整數陣列的值、該陣列中的起始位置及長度。

String(SByte*)

將該類別的新實例 String 初始化為指向 8 位元有符號整數陣列的指標所指示的值。

欄位

名稱 Description
Empty

代表空字串。 此欄位僅供讀取。

屬性

名稱 Description
Chars[Int32]

取得 Char 物件在當前 String 物件指定位置的位置。

Length

取得目前 String 物件中的字元數。

方法

名稱 Description
Clone()

回傳此實例 String的參考。

Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)

比較兩個指定 String 物件的子串,忽略或尊重其情況,並利用文化特定資訊影響比較,並回傳一個整數,表示它們在排序順序中的相對位置。

Compare(String, Int32, String, Int32, Int32, Boolean)

比較兩個指定 String 物件的子串,忽略或尊重它們的格,並回傳一個整數表示它們在排序順序中的相對位置。

Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)

利用指定的比較選項與文化特定資訊比較兩個指定 String 物件的子串來影響比較,並回傳一個整數,表示兩個子串在排序順序中的關係。

Compare(String, Int32, String, Int32, Int32, StringComparison)

利用指定規則比較兩個指定 String 物件的子字串,並回傳一個整數,表示它們在排序順序中的相對位置。

Compare(String, Int32, String, Int32, Int32)

比較兩個指定 String 物件的子串,並回傳一個整數,表示它們在排序順序中的相對位置。

Compare(String, String, Boolean, CultureInfo)

比較兩個指定 String 物件,忽略或尊重其情況,並利用文化特定資訊影響比較,並回傳一個整數表示它們在排序順序中的相對位置。

Compare(String, String, Boolean)

比較兩個指定 String 物件,忽略或尊重其大小,並回傳一個整數,表示它們在排序順序中的相對位置。

Compare(String, String, CultureInfo, CompareOptions)

利用指定的比較選項與文化特定資訊比較兩個指定 String 物件,影響比較結果,並回傳一個整數,顯示兩字串在排序順序中的關係。

Compare(String, String, StringComparison)

使用指定規則比較兩個指定 String 物件,並回傳一個整數,表示它們在排序順序中的相對位置。

Compare(String, String)

比較兩個指定的 String 物件,並回傳一個整數,表示它們在排序順序中的相對位置。

CompareOrdinal(String, Int32, String, Int32, Int32)

透過評估兩個指定物件中對應String物件的數值,比較兩個指定Char物件的子串。

CompareOrdinal(String, String)

透過評估每個字串中對應String物件的數值,比較兩個指定Char物件。

CompareTo(Object)

比較此實例與指定的 Object 實例,並表示該實例是否在排序順序中與指定 Object實例之前、後或出現的位置相同。

CompareTo(String)

比較此實例與指定 String 物件,並指示該實例是否在排序順序中與指定字串相同位置。

Concat(IEnumerable<String>)

串接一個型態IEnumerable<T>為 的構造String集合的成員。

Concat(Object, Object, Object, Object)

串連四個指定物件的字串表示,以及選擇性可變長度參數清單中指定的任何物件。

Concat(Object, Object, Object)

串連三個指定物件的字串表示。

Concat(Object, Object)

串連兩個指定物件的字串表示。

Concat(Object)

建立指定物件的字串表示。

Concat(Object[])

串接指定陣列中 Object 元素的字串表示。

Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>)

串連四個指定唯讀字元範圍的字串表示。

Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>)

串連三個指定唯讀字元範圍的字串表示。

Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>)

串連兩個指定唯讀字元範圍的字串表示。

Concat(ReadOnlySpan<Object>)

串連指定之物件範圍中元素的字串表示。

Concat(ReadOnlySpan<String>)

串接指定張成 String的元素。

Concat(String, String, String, String)

串接四個指定的實例 String

Concat(String, String, String)

串接三個指定的實例 String

Concat(String, String)

串接兩個指定的實例 String

Concat(String[])

串接指定 String 陣列的元素。

Concat<T>(IEnumerable<T>)

串接實作的 IEnumerable<T> 成員。

Contains(Char, StringComparison)

回傳一個值,表示指定字元是否出現在該字串中,並使用指定的比較規則。

Contains(Char)

回傳一個值,表示指定字元是否出現在該字串中。

Contains(Rune, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

Contains(Rune)

以 UTF-16 程式代碼單位序列表示文字。

Contains(String, StringComparison)

回傳一個值,表示指定字串是否出現在該字串中,並使用指定的比較規則。

Contains(String)

回傳一個值,表示指定子字串是否出現在此字串中。

Copy(String)
已淘汰.

建立一個與指定String值相同的新實例String

CopyTo(Int32, Char[], Int32, Int32)

在此實例中,將指定數量的字元從指定位置複製到一個 Unicode 字元陣列中的指定位置。

CopyTo(Span<Char>)

將此字串的內容複製到目的區間。

Create(IFormatProvider, DefaultInterpolatedStringHandler)

透過指定的提供者來控制指定的插值字串的格式化,建立新的字串。

Create(IFormatProvider, Span<Char>, DefaultInterpolatedStringHandler)

透過指定的提供者來控制指定的插值字串的格式化,建立新的字串。

Create<TState>(Int32, TState, SpanAction<Char,TState>)

建立一個特定長度的新字串,並在建立後使用指定的回調初始化。

EndsWith(Char, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

EndsWith(Char)

判斷此字串實例的結尾是否符合指定字元。

EndsWith(Rune, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

EndsWith(Rune)

以 UTF-16 程式代碼單位序列表示文字。

EndsWith(String, Boolean, CultureInfo)

判斷該字串實例的末尾是否與指定字串相符,並使用指定的文化進行比較。

EndsWith(String, StringComparison)

透過指定的比較選項比較,判斷該字串實例的末尾是否與指定字串相符。

EndsWith(String)

判斷此字串實例的結尾是否與指定字串相符。

EnumerateRunes()

從此字串回傳一個 Rune 枚舉。

Equals(Object)

判斷此實例與指定物件(必須同時也是 String 物件)值是否相同。

Equals(String, String, StringComparison)

判斷兩個指定 String 物件的值是否相同。 參數指定比較中使用的文化、案例及排序規則。

Equals(String, String)

判斷兩個指定 String 物件的值是否相同。

Equals(String, StringComparison)

判斷此字串與指定 String 物件值是否相同。 參數指定比較中使用的文化、案例及排序規則。

Equals(String)

判斷此實例與另一個指定 String 物件是否具有相同值。

Format(IFormatProvider, CompositeFormat, Object[])

以指定格式中對應物件的字串表示來取代格式 CompositeFormat 項目。

Format(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

以指定格式中對應物件的字串表示來取代格式 CompositeFormat 項目。

Format(IFormatProvider, String, Object, Object, Object)

將字串中的格式專案取代為三個指定物件的字串表示。 參數提供特定文化特性的格式資訊。

Format(IFormatProvider, String, Object, Object)

將字串中的格式專案取代為兩個指定物件的字串表示。 參數提供特定文化特性的格式資訊。

Format(IFormatProvider, String, Object)

將指定字串中的格式專案或專案取代為對應物件的字串表示。 參數提供特定文化特性的格式資訊。

Format(IFormatProvider, String, Object[])

將字串中的格式專案取代為指定數位中對應物件的字串表示。 參數提供特定文化特性的格式資訊。

Format(IFormatProvider, String, ReadOnlySpan<Object>)

將字串中的格式專案取代為指定範圍中對應物件的字串表示。 參數提供特定文化特性的格式資訊。

Format(String, Object, Object, Object)

將字串中的格式專案取代為三個指定物件的字串表示。

Format(String, Object, Object)

將字串中的格式專案取代為兩個指定物件的字串表示。

Format(String, Object)

以指定物件的字串表示取代字串中的一或多個格式專案。

Format(String, Object[])

將指定字串中的格式專案取代為指定數位中對應物件的字串表示。

Format(String, ReadOnlySpan<Object>)

將指定字串中的格式專案取代為指定範圍中對應物件的字串表示。

Format<TArg0,TArg1,TArg2>(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

以指定格式中對應物件的字串表示來取代格式 CompositeFormat 項目。

Format<TArg0,TArg1>(IFormatProvider, CompositeFormat, TArg0, TArg1)

以指定格式中對應物件的字串表示來取代格式 CompositeFormat 項目。

Format<TArg0>(IFormatProvider, CompositeFormat, TArg0)

以指定格式中對應物件的字串表示來取代格式 CompositeFormat 項目。

GetEnumerator()

取得一個物件,可以遍歷該字串中的各個字元。

GetHashCode()

回傳此字串的雜湊碼。

GetHashCode(ReadOnlySpan<Char>, StringComparison)

會依照指定規則回傳該只讀字元區間的雜湊碼。

GetHashCode(ReadOnlySpan<Char>)

回傳所提供唯讀字元區間的雜湊碼。

GetHashCode(StringComparison)

會依照指定規則回傳此字串的雜湊碼。

GetPinnableReference()

回傳指向字串中索引為零的元素的參考。

此方法旨在支援 .NET 編譯器,並非使用者程式碼所呼叫。

GetType()

取得目前實例的 Type

(繼承來源 Object)
GetTypeCode()

退還課程TypeCodeString

IndexOf(Char, Int32, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Char, Int32, Int32)

報告此時指定字元首次出現的零為基礎索引。 搜尋從指定的字元位置開始,並檢視指定數量的字元位置。

IndexOf(Char, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Char, Int32)

報告該字串中指定 Unicode 字元首次出現的以零為基礎的索引。 搜尋從指定的字元位置開始。

IndexOf(Char, StringComparison)

報告該字串中指定 Unicode 字元首次出現的以零為基礎的索引。 參數指定該字元應使用的搜尋類型。

IndexOf(Char)

報告該字串中指定 Unicode 字元首次出現的以零為基礎的索引。

IndexOf(Rune, Int32, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Rune, Int32, Int32)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Rune, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Rune, Int32)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Rune, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(Rune)

以 UTF-16 程式代碼單位序列表示文字。

IndexOf(String, Int32, Int32, StringComparison)

報告指定字串首次出現於當前 String 物件的零為基礎索引。 參數會指定當前字串的起始搜尋位置、目前字串中可搜尋的字元數,以及該字串所要使用的搜尋類型。

IndexOf(String, Int32, Int32)

報告該字串在此實例中首次出現的零為基礎的索引。 搜尋從指定的字元位置開始,並檢視指定數量的字元位置。

IndexOf(String, Int32, StringComparison)

報告指定字串首次出現於當前 String 物件的零為基礎索引。 參數指定當前字串的起始搜尋位置及指定字串所用的搜尋類型。

IndexOf(String, Int32)

報告該字串在此實例中首次出現的零為基礎的索引。 搜尋從指定的字元位置開始。

IndexOf(String, StringComparison)

報告指定字串首次出現於當前 String 物件的零為基礎索引。 參數會指定要用於指定字串的搜尋類型。

IndexOf(String)

報告該字串在此實例中首次出現的零為基礎的索引。

IndexOfAny(Char[], Int32, Int32)

報告此例中任意 Unicode 字元陣列中首次出現的零為基礎索引。 搜尋從指定的字元位置開始,並檢視指定數量的字元位置。

IndexOfAny(Char[], Int32)

報告此例中任意 Unicode 字元陣列中首次出現的零為基礎索引。 搜尋從指定的字元位置開始。

IndexOfAny(Char[])

報告此例中任意 Unicode 字元陣列中首次出現的零為基礎索引。

Insert(Int32, String)

回傳一個新字串,該字串在此實例中插入指定的字串於指定索引位置。

Intern(String)

取得系統對指定 String的參考。

IsInterned(String)

取得指定 String的參考。

IsNormalized()

表示此字串是否屬於 Unicode 正規化形式 C。

IsNormalized(NormalizationForm)

表示此字串是否屬於指定的 Unicode 正規化形式。

IsNullOrEmpty(String)

表示指定的字串 null 是空字串(「」)。

IsNullOrWhiteSpace(String)

表示指定字串 null是空字串,還是僅包含空白字元。

Join(Char, Object[])

使用每個成員之間的指定分隔符,串連 物件陣列的字串表示。

Join(Char, ReadOnlySpan<Object>)

使用每個成員之間的指定分隔符,串連物件範圍的字串表示。

Join(Char, ReadOnlySpan<String>)

使用每個成員之間的指定分隔符,串連字串範圍。

Join(Char, String[], Int32, Int32)

串接一組字串,使用每個成員間指定的分隔符,從位於該value位置的元素startIndex開始,串接至count元素。

Join(Char, String[])

使用每個成員之間的指定分隔符串連字串陣列。

Join(String, IEnumerable<String>)

利用指定的分隔符串接一個型別IEnumerable<T>為 的構造String集合的成員。

Join(String, Object[])

使用每個項目之間的指定分隔符,串連物件數位的專案。

Join(String, ReadOnlySpan<Object>)

使用每個成員之間的指定分隔符,串連物件範圍的字串表示。

Join(String, ReadOnlySpan<String>)

使用每個成員之間的指定分隔符,串連字串範圍。

Join(String, String[], Int32, Int32)

使用每個元素之間的指定分隔符,串連字串陣列的指定專案。

Join(String, String[])

使用每個元素之間的指定分隔符,串連字串陣列的所有元素。

Join<T>(Char, IEnumerable<T>)

使用每個成員之間的指定分隔符,串連集合的成員。

Join<T>(String, IEnumerable<T>)

使用每個成員之間的指定分隔符,串連集合的成員。

LastIndexOf(Char, Int32, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Char, Int32, Int32)

報告這個實例中子字串中最後一個出現之 Unicode 字元之以零起始的索引位置。 搜尋會從指定的字元位置開始,然後嚮往回嚮往字串開頭,以取得指定數目的字元位置。

LastIndexOf(Char, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Char, Int32)

報告這個實例中指定 Unicode 字元最後一次出現之以零起始的索引位置。 搜尋會從指定的字元位置開始,然後嚮往字串開頭。

LastIndexOf(Char, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Char)

報告這個實例中指定 Unicode 字元最後一次出現之以零起始的索引位置。

LastIndexOf(Rune, Int32, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Rune, Int32, Int32)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Rune, Int32, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Rune, Int32)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Rune, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(Rune)

以 UTF-16 程式代碼單位序列表示文字。

LastIndexOf(String, Int32, Int32, StringComparison)

報告這個實例中最後一個出現指定字串之以零起始的索引位置。 搜尋會從指定的字元位置開始,然後嚮往回嚮往字串開頭,以取得指定的字元位置數目。 參數會指定搜尋指定字串時要執行的比較類型。

LastIndexOf(String, Int32, Int32)

報告這個實例中最後一個出現指定字串之以零起始的索引位置。 搜尋會從指定的字元位置開始,然後嚮往回嚮往字串開頭,以取得指定數目的字元位置。

LastIndexOf(String, Int32, StringComparison)

報告指定字串在當前 String 物件中最後一次出現的零為基礎的索引。 搜尋會從指定的字元位置開始,然後嚮往字串開頭。 參數會指定搜尋指定字串時要執行的比較類型。

LastIndexOf(String, Int32)

報告這個實例中最後一個出現指定字串之以零起始的索引位置。 搜尋會從指定的字元位置開始,然後嚮往字串開頭。

LastIndexOf(String, StringComparison)

報告指定字串在當前 String 物件中最後一次出現的零為基礎的索引。 參數會指定要用於指定字串的搜尋類型。

LastIndexOf(String)

報告這個實例中最後一個出現指定字串之以零起始的索引位置。

LastIndexOfAny(Char[], Int32, Int32)

報告 Unicode 陣列中一個或多個字元最後一次出現時的零為基礎索引位置。 搜尋會從指定的字元位置開始,然後嚮往回嚮往字串開頭,以取得指定數目的字元位置。

LastIndexOfAny(Char[], Int32)

報告 Unicode 陣列中一個或多個字元最後一次出現時的零為基礎索引位置。 搜尋會從指定的字元位置開始,然後嚮往字串開頭。

LastIndexOfAny(Char[])

報告 Unicode 陣列中一個或多個字元最後一次出現時的零為基礎索引位置。

MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
Normalize()

回傳一個新字串,其文本值與此字串相同,但其二進位表示為 Unicode 正規化形式 C。

Normalize(NormalizationForm)

回傳一個新字串,其文本值與此字串相同,但其二進位表示為指定的 Unicode 正規化形式。

PadLeft(Int32, Char)

回傳一個新字串,透過在左側用指定的 Unicode 字元填充字元,使字元右對齊,達到指定的總長度。

PadLeft(Int32)

回傳一個新字串,透過在左側用空格填充字元,將字元右對齊,並設定指定的總長度。

PadRight(Int32, Char)

回傳一個新字串,透過在右側用指定的 Unicode 字元填充字元,使字元左對齊,達到指定的總長度。

PadRight(Int32)

回傳一個新字串,透過在右側用空格填充字元,使字元左對齊,並設定指定的總長度。

Remove(Int32, Int32)

回傳一個新字串,該字串中已刪除當前實例中從指定位置開始的指定字元數。

Remove(Int32)

回傳一個新字串,該字串中目前實例中從指定位置開始並一直到最後一個位置的所有字元都已被刪除。

Replace(Char, Char)

回傳一個新字串,該字串中該實例中指定 Unicode 字元的所有出現都被替換為另一個指定的 Unicode 字元。

Replace(Rune, Rune)

以 UTF-16 程式代碼單位序列表示文字。

Replace(String, String, Boolean, CultureInfo)

回傳一個新字串,將當前實例中指定字串的所有出現都替換為另一個指定字串,使用提供的文化與大小寫敏感度。

Replace(String, String, StringComparison)

回傳一個新字串,將當前實例中指定字串的所有出現都替換為另一個指定的字串,並使用提供的比較型別。

Replace(String, String)

回傳一個新字串,將當前實例中指定字串的所有出現都被替換為另一個指定的字串。

ReplaceLineEndings()

將目前字串中所有換行序列替換為 NewLine

ReplaceLineEndings(String)

將目前字串中所有換行序列替換為 replacementText

Split(Char, Int32, StringSplitOptions)

根據提供的字元分隔符,將字串分割成最大子字串數目,選擇性地省略結果中的空白子字串。

Split(Char, StringSplitOptions)

根據指定的分隔字元,將字串分割成子字串,並選擇性地將字串分割成子字串。

Split(Char[], Int32, StringSplitOptions)

根據指定的分隔字元和選擇性選項,將字串分割成最大子字串數目。

Split(Char[], Int32)

根據指定的分隔字元,將字串分割成最大子字串數目。

Split(Char[], StringSplitOptions)

根據指定的分隔字元和選項,將字串分割成子字串。

Split(Char[])

根據指定的分隔字元,將字串分割成子字串。

Split(ReadOnlySpan<Char>)

根據指定的分隔字元,將字串分割成子字串。

Split(Rune, Int32, StringSplitOptions)

以 UTF-16 程式代碼單位序列表示文字。

Split(Rune, StringSplitOptions)

以 UTF-16 程式代碼單位序列表示文字。

Split(String, Int32, StringSplitOptions)

根據指定的分隔字串,將字串分割成最大子字串數目,並選擇性地將字串分割成最大數目。

Split(String, StringSplitOptions)

將字串分割成以提供的字串分隔符為基礎的子字串。

Split(String[], Int32, StringSplitOptions)

根據指定的分隔字串和選擇性選項,將字串分割成子字串數目上限。

Split(String[], StringSplitOptions)

根據指定的分隔字串,將字串分割成子字串串,並選擇性地將字串分割成子字串。

StartsWith(Char, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

StartsWith(Char)

判斷此字串實例是否以指定字元開頭。

StartsWith(Rune, StringComparison)

以 UTF-16 程式代碼單位序列表示文字。

StartsWith(Rune)

以 UTF-16 程式代碼單位序列表示文字。

StartsWith(String, Boolean, CultureInfo)

判斷該字串實例的開頭是否與指定字串相符,並使用指定的文化進行比較。

StartsWith(String, StringComparison)

透過指定的比較選項,判斷該字串實例的開頭是否與指定字串相符。

StartsWith(String)

判斷此字串實例的開頭是否與指定字串相符。

Substring(Int32, Int32)

從此實例中擷取一個子字串。 子字串從指定的字元位置開始,並具有指定的長度。

Substring(Int32)

從此實例中擷取一個子字串。 子字串從指定的字元位置開始,並一直延伸到字串的末尾。

ToCharArray()

將此處的字元複製到 Unicode 字元陣列。

ToCharArray(Int32, Int32)

在此實例中,將指定子串中的字元複製到 Unicode 字元陣列。

ToLower()

回傳該字串的轉為小寫的副本。

ToLower(CultureInfo)

回傳該字串的副本,轉換為小寫,並依照指定文化的大小寫規則。

ToLowerInvariant()

回傳此物件的副本 String ,並使用不變培養的大小寫規則轉換為小寫。

ToString()

回傳此實例 String;未進行實際轉換。

ToString(IFormatProvider)

回傳此實例 String;未進行實際轉換。

ToUpper()

回傳該字串的複製品,已轉換為大寫字母。

ToUpper(CultureInfo)

回傳該字串的複製品,並依照指定文化的大小寫規則轉換為大寫字母。

ToUpperInvariant()

回傳該物件的副本 String ,並依照不變培養的格式規則轉換為大寫字母。

Trim()

移除目前字串中所有前置與後方空白字元。

Trim(Char)

移除目前字串中所有前後字元的實例。

Trim(Char[])

從目前字串中移除陣列中指定的一組字元的所有前後出現。

Trim(Rune)

以 UTF-16 程式代碼單位序列表示文字。

TrimEnd()

從目前字串中移除所有尾端空格符。

TrimEnd(Char)

從目前字串中移除字元的所有尾端專案。

TrimEnd(Char[])

從目前字串中移除陣列中指定的一組字元的所有尾端專案。

TrimEnd(Rune)

以 UTF-16 程式代碼單位序列表示文字。

TrimStart()

從目前字串中移除所有前置空格符。

TrimStart(Char)

從目前字串中移除指定字元的所有前置專案。

TrimStart(Char[])

從目前字串中移除陣列中指定的一組字元的所有前置專案。

TrimStart(Rune)

以 UTF-16 程式代碼單位序列表示文字。

TryCopyTo(Span<Char>)

將此字串的內容複製到目的區間。

操作員

名稱 Description
Equality(String, String)

判斷兩個指定字串的值是否相同。

Implicit(String to ReadOnlySpan<Char>)

定義了將特定字串隱含轉換為唯讀字元區段的方法。

Inequality(String, String)

判斷兩個指定字串的值是否不同。

明確介面實作

名稱 Description
IComparable.CompareTo(Object)

比較此實例與指定的 Object 實例,並表示該實例是否在排序順序中與指定 Object實例之前、後或出現的位置相同。

IConvertible.GetTypeCode()

退還課程TypeCodeString

IConvertible.ToBoolean(IFormatProvider)

關於此成員的描述,請參見 ToBoolean(IFormatProvider)

IConvertible.ToByte(IFormatProvider)

關於此成員的描述,請參見 ToByte(IFormatProvider)

IConvertible.ToChar(IFormatProvider)

關於此成員的描述,請參見 ToChar(IFormatProvider)

IConvertible.ToDateTime(IFormatProvider)

關於此成員的描述,請參見 ToDateTime(IFormatProvider)

IConvertible.ToDecimal(IFormatProvider)

關於此成員的描述,請參見 ToDecimal(IFormatProvider)

IConvertible.ToDouble(IFormatProvider)

關於此成員的描述,請參見 ToDouble(IFormatProvider)

IConvertible.ToInt16(IFormatProvider)

關於此成員的描述,請參見 ToInt16(IFormatProvider)

IConvertible.ToInt32(IFormatProvider)

關於此成員的描述,請參見 ToInt32(IFormatProvider)

IConvertible.ToInt64(IFormatProvider)

關於此成員的描述,請參見 ToInt64(IFormatProvider)

IConvertible.ToSByte(IFormatProvider)

關於此成員的描述,請參見 ToSByte(IFormatProvider)

IConvertible.ToSingle(IFormatProvider)

關於此成員的描述,請參見 ToSingle(IFormatProvider)

IConvertible.ToString(IFormatProvider)

關於此成員的描述,請參見 ToString(IFormatProvider)

IConvertible.ToType(Type, IFormatProvider)

關於此成員的描述,請參見 ToType(Type, IFormatProvider)

IConvertible.ToUInt16(IFormatProvider)

關於此成員的描述,請參見 ToUInt16(IFormatProvider)

IConvertible.ToUInt32(IFormatProvider)

關於此成員的描述,請參見 ToUInt32(IFormatProvider)

IConvertible.ToUInt64(IFormatProvider)

關於此成員的描述,請參見 ToUInt64(IFormatProvider)

IEnumerable.GetEnumerator()

回傳一個列舉子,會遍歷目前的 String 物件。

IEnumerable<Char>.GetEnumerator()

回傳一個列舉子,會遍歷目前的 String 物件。

IParsable<String>.Parse(String, IFormatProvider)

將字串剖析成值。

IParsable<String>.TryParse(String, IFormatProvider, String)

以 UTF-16 程式代碼單位序列表示文字。

ISpanParsable<String>.Parse(ReadOnlySpan<Char>, IFormatProvider)

將字元範圍剖析為值。

ISpanParsable<String>.TryParse(ReadOnlySpan<Char>, IFormatProvider, String)

以 UTF-16 程式代碼單位序列表示文字。

擴充方法

名稱 Description
Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)

在序列上套用累加器函式。 指定的種子值會當做初始累加器值使用,而指定的函式則用來選取結果值。

Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)

在序列上套用累加器函式。 指定的種子值會當做初始累加器值使用。

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)

在序列上套用累加器函式。

AggregateBy<TSource,TKey,TAccumulate>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TKey,TAccumulate>, Func<TAccumulate,TSource,TAccumulate>, IEqualityComparer<TKey>)

對序列套用累加函數,依鍵分組結果。

AggregateBy<TSource,TKey,TAccumulate>(IEnumerable<TSource>, Func<TSource, TKey>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, IEqualityComparer<TKey>)

對序列套用累加函數,依鍵分組結果。

All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

判斷序列的所有專案是否符合條件。

Ancestors<T>(IEnumerable<T>, XName)

傳回元素的篩選集合,其中包含來源集合中每個節點的上階。 集合中只會包含具有相符 XName 的專案。

Ancestors<T>(IEnumerable<T>)

傳回專案集合,其中包含來源集合中每個節點的上階。

Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

判斷序列的任何專案是否符合條件。

Any<TSource>(IEnumerable<TSource>)

判斷序列是否包含任何專案。

Append<TSource>(IEnumerable<TSource>, TSource)

將值附加至序列結尾。

AsEnumerable<TSource>(IEnumerable<TSource>)

傳回 IEnumerable<T> 類型的輸入。

AsMemory(String, Index)

在目標字串的某個部分上建立新 ReadOnlyMemory<Char> 索引,從指定索引開始。

AsMemory(String, Int32, Int32)

在目標字串的一段位置以長度開始的部分建立新 ReadOnlyMemory<Char> 字串。

AsMemory(String, Int32)

在目標字串的某個部分,從指定字元位置開始建立新 ReadOnlyMemory<Char> 字串。

AsMemory(String, Range)

在目標字串的特定範圍內建立新 ReadOnlyMemory<Char> 一個。

AsMemory(String)

在目標字串的部分建立新的 ReadOnlyMemory<Char>

AsParallel(IEnumerable)

啟用查詢的平行處理。

AsParallel<TSource>(IEnumerable<TSource>)

啟用查詢的平行處理。

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryable

AsQueryable<TElement>(IEnumerable<TElement>)

將泛型 IEnumerable<T> 轉換成泛型 IQueryable<T>

AsSpan(String, Index)

從指定位置到字串末端,在目標字串的一部分上建立新 ReadOnlySpan<T> 字串。

AsSpan(String, Int32, Int32)

從指定位置建立目標字串部分的只讀區間,且需特定字元數。

AsSpan(String, Int32)

建立一個新的唯讀區間,涵蓋目標字串從指定位置到字串末端的部分。

AsSpan(String, Range)

利用範圍起始與結束索引,在目標字串的一部分上建立新資料 ReadOnlySpan<T>

AsSpan(String)

在字串上建立一個新的唯讀區間。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

計算 Decimal 值序列的平均值,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

計算 Double 值序列的平均值,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

計算 Int32 值序列的平均值,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

計算 Int64 值序列的平均值,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Decimal 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Double 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Int32 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Int64 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Single 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

計算 Single 值序列的平均值,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。

Chunk<TSource>(IEnumerable<TSource>, Int32)

將序列的專案分割成大社區塊,最多 size

Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

串連兩個序列。

Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T>,判斷序列是否包含指定的專案。

Contains<TSource>(IEnumerable<TSource>, TSource)

判斷序列是否使用預設相等比較子來包含指定的專案。

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

DataRow 物件複製到指定的 DataTable,指定輸入 IEnumerable<T> 物件,其中泛型參數 TDataRow

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

DataRow 物件複製到指定的 DataTable,指定輸入 IEnumerable<T> 物件,其中泛型參數 TDataRow

CopyToDataTable<T>(IEnumerable<T>)

傳回包含 DataTable 物件複本的 DataRow,指定泛型參數 IEnumerable<T>T的輸入 DataRow 物件。

Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回數位,代表指定序列中滿足條件的項目數目。

Count<TSource>(IEnumerable<TSource>)

傳回序列中的項目數目。

CountBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

回傳來源序列中依鍵分組的元素數量。

DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)

如果序列是空的,則傳回指定序列的專案或單一集合中的指定值。

DefaultIfEmpty<TSource>(IEnumerable<TSource>)

如果序列是空的,則傳回指定序列的專案或單一集合中型別參數的預設值。

DescendantNodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和專案之子代節點的集合。

Descendants<T>(IEnumerable<T>, XName)

傳回篩選的專案集合,其中包含來源集合中每個元素和檔的子代專案。 集合中只會包含具有相符 XName 的專案。

Descendants<T>(IEnumerable<T>)

傳回專案集合,其中包含來源集合中每個元素和檔的子代專案。

Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,從序列傳回不同的專案。

Distinct<TSource>(IEnumerable<TSource>)

使用預設相等比較子來比較值,從序列傳回不同的專案。

DistinctBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,並使用指定的比較子來比較索引鍵,從序列傳回不同的專案。

DistinctBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,從序列傳回不同的專案。

ElementAt<TSource>(IEnumerable<TSource>, Index)

傳回序列中指定索引處的專案。

ElementAt<TSource>(IEnumerable<TSource>, Int32)

傳回序列中指定索引處的專案。

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index)

傳回序列中指定索引處的專案,如果索引超出範圍,則傳回預設值。

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32)

傳回序列中指定索引處的專案,如果索引超出範圍,則傳回預設值。

Elements<T>(IEnumerable<T>, XName)

傳回來源集合中每個專案和檔之子項目的篩選集合。 集合中只會包含具有相符 XName 的專案。

Elements<T>(IEnumerable<T>)

傳回來源集合中每個專案和檔的子專案集合。

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,產生兩個序列的集合差異。

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子來比較值,產生兩個序列的集合差異。

ExceptBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合差異。

ExceptBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合差異。

First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定條件的第一個專案。

First<TSource>(IEnumerable<TSource>)

傳回序列的第一個專案。

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

傳回序列中符合條件的第一個專案,如果沒有找到這類專案,則傳回指定的預設值。

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列的第一個專案,如果找不到這類專案,則為符合條件或預設值。

FirstOrDefault<TSource>(IEnumerable<TSource>, TSource)

傳回序列的第一個專案,如果序列不包含任何專案,則傳回指定的預設值。

FirstOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的第一個專案,如果序列不包含任何專案,則傳回預設值。

FullJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>)

以 UTF-16 程式代碼單位序列表示文字。

FullJoin<TOuter,TInner,TKey>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, IEqualityComparer<TKey>)

以 UTF-16 程式代碼單位序列表示文字。

GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>, TResult>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,將序列的專案分組,並從每個群組及其索引鍵建立結果值。 索引鍵值是使用指定的比較子來比較,而每個群組的元素都是使用指定的函式來投影。

GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>)

根據指定的索引鍵選取器函式,將序列的專案分組,並從每個群組及其索引鍵建立結果值。 每個群組的項目都會使用指定的函式來投影。

GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據索引鍵選取器函式,將序列的專案分組。 索引鍵是使用比較子來比較,而且每個群組的元素都是使用指定的函式來投影。

GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

根據指定的索引鍵選取器函式將序列的專案分組,並使用指定的函式來投影每個群組的專案。

GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,將序列的專案分組,並從每個群組及其索引鍵建立結果值。 使用指定的比較子來比較索引鍵。

GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>)

根據指定的索引鍵選取器函式,將序列的專案分組,並從每個群組及其索引鍵建立結果值。

GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式將序列的專案分組,並使用指定的比較子比較索引鍵。

GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,將序列的專案分組。

GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>, TResult>, IEqualityComparer<TKey>)

根據索引鍵相等將兩個序列的專案相互關聯,並將結果分組。 指定的 IEqualityComparer<T> 可用來比較索引鍵。

GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>, TResult>)

根據索引鍵的相等性,將兩個序列的專案相互關聯,並將結果分組。 默認相等比較子可用來比較索引鍵。

GroupJoin<TOuter,TInner,TKey>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, IEqualityComparer<TKey>)

以 UTF-16 程式代碼單位序列表示文字。

Index<TSource>(IEnumerable<TSource>)

傳回可列舉,將元素的索引併入 Tuple 中。

InDocumentOrder<T>(IEnumerable<T>)

傳回包含來源集合中所有節點的節點集合,依檔順序排序。

Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,產生兩個序列的集合交集。

Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子比較值來產生兩個序列的集合交集。

IntersectBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合交集。

IntersectBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合交集。

IsNormalized(String, NormalizationForm)

表示字串是否屬於指定的 Unicode 正規化形式。

IsNormalized(String)

表示指定的字串是否採用 Unicode 正規化形式 C。

Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>)

根據匹配的鍵數關聯兩個序列的元素。 指定的 IEqualityComparer<T> 可用來比較索引鍵。

Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>)

根據匹配的鍵數關聯兩個序列的元素。 默認相等比較子可用來比較索引鍵。

Join<TOuter,TInner,TKey>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, IEqualityComparer<TKey>)

以 UTF-16 程式代碼單位序列表示文字。

Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回符合指定條件之序列的最後一個專案。

Last<TSource>(IEnumerable<TSource>)

傳回序列的最後一個專案。

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

傳回符合條件之序列的最後一個專案,如果沒有找到這類專案,則傳回指定的預設值。

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列的最後一個專案,如果找不到這類專案,則為符合條件或預設值。

LastOrDefault<TSource>(IEnumerable<TSource>, TSource)

傳回序列的最後一個專案,如果序列不包含任何專案,則傳回指定的預設值。

LastOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的最後一個專案,如果序列不包含任何專案,則傳回預設值。

LeftJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>)

根據匹配的鍵數關聯兩個序列的元素。 指定的 IEqualityComparer<T> 可用來比較索引鍵。

LeftJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>)

根據匹配的鍵數關聯兩個序列的元素。 默認相等比較子可用來比較索引鍵。

LeftJoin<TOuter,TInner,TKey>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, IEqualityComparer<TKey>)

以 UTF-16 程式代碼單位序列表示文字。

LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回 Int64,代表序列中滿足條件的項目數目。

LongCount<TSource>(IEnumerable<TSource>)

傳回代表序列中項目總數的 Int64

Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

在泛型序列的每個專案上叫用轉換函式,並傳回產生的最大值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

在序列的每個元素上叫用轉換函式,並傳回最大 Decimal 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

在序列的每個元素上叫用轉換函式,並傳回最大 Double 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

在序列的每個元素上叫用轉換函式,並傳回最大 Int32 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

在序列的每個元素上叫用轉換函式,並傳回最大 Int64 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

在序列的每個元素上叫用轉換函式,並傳回可為 Null 的最大 Decimal 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

在序列的每個元素上叫用轉換函式,並傳回可為 Null 的最大 Double 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

在序列的每個元素上叫用轉換函式,並傳回可為 Null 的最大 Int32 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

在序列的每個元素上叫用轉換函式,並傳回可為 Null 的最大 Int64 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

在序列的每個元素上叫用轉換函式,並傳回可為 Null 的最大 Single 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

在序列的每個元素上叫用轉換函式,並傳回最大 Single 值。

Max<TSource>(IEnumerable<TSource>, IComparer<TSource>)

傳回泛型序列中的最大值。

Max<TSource>(IEnumerable<TSource>)

傳回泛型序列中的最大值。

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,傳回泛型序列中的最大值。

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,傳回泛型序列中的最大值。

Min<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

在泛型序列的每個專案上叫用轉換函式,並傳回產生的最小值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

在序列的每個元素上叫用轉換函式,並傳回最小值 Decimal 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

在序列的每個元素上叫用轉換函式,並傳回最小值 Double 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

在序列的每個元素上叫用轉換函式,並傳回最小值 Int32 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

在序列的每個元素上叫用轉換函式,並傳回最小值 Int64 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

在序列的每個專案上叫用轉換函式,並傳回可為 null 的最小值 Decimal 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

在序列的每個專案上叫用轉換函式,並傳回可為 null 的最小值 Double 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

在序列的每個專案上叫用轉換函式,並傳回可為 null 的最小值 Int32 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

在序列的每個專案上叫用轉換函式,並傳回可為 null 的最小值 Int64 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

在序列的每個專案上叫用轉換函式,並傳回可為 null 的最小值 Single 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

在序列的每個元素上叫用轉換函式,並傳回最小值 Single 值。

Min<TSource>(IEnumerable<TSource>, IComparer<TSource>)

傳回泛型序列中的最小值。

Min<TSource>(IEnumerable<TSource>)

傳回泛型序列中的最小值。

MinBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,傳回泛型序列中的最小值。

MinBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,傳回泛型序列中的最小值。

Nodes<T>(IEnumerable<T>)

傳回來源集合中每個檔和專案之子節點的集合。

Normalize(String, NormalizationForm)

將字串正規化為指定的 Unicode 正規化形式。

Normalize(String)

將字串正規化為 Unicode 正規化形式 C。

OfType<TResult>(IEnumerable)

根據指定的型別篩選 IEnumerable 的專案。

Order<T>(IEnumerable<T>, IComparer<T>)

以遞增順序排序序列的專案。

Order<T>(IEnumerable<T>)

以遞增順序排序序列的專案。

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

使用指定的比較子,以遞增順序排序序列的專案。

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據索引鍵,以遞增順序排序序列的專案。

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

使用指定的比較子,以遞減順序排序序列的專案。

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據索引鍵,以遞減順序排序序列的專案。

OrderDescending<T>(IEnumerable<T>, IComparer<T>)

依遞減順序排序序列的專案。

OrderDescending<T>(IEnumerable<T>)

依遞減順序排序序列的專案。

Prepend<TSource>(IEnumerable<TSource>, TSource)

將值加入序列的開頭。

Remove<T>(IEnumerable<T>)

從來源集合的父節點中移除每個節點。

Reverse<TSource>(IEnumerable<TSource>)

反轉序列中項目的順序。

RightJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>)

根據匹配的鍵數關聯兩個序列的元素。 指定的 IEqualityComparer<T> 可用來比較索引鍵。

RightJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>)

根據匹配的鍵數關聯兩個序列的元素。 默認相等比較子可用來比較索引鍵。

RightJoin<TOuter,TInner,TKey>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, IEqualityComparer<TKey>)

以 UTF-16 程式代碼單位序列表示文字。

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>)

藉由合併元素的索引,將序列的每個專案投影成新的表單。

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

將序列的每個專案投影成新的表單。

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

將序列的每個專案投影到 IEnumerable<T>,將產生的序列扁平化成一個序列,並在其中的每個元素上叫用結果選取器函式。

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

將序列的每個專案投影到 IEnumerable<T>,將產生的序列扁平化成一個序列,並在其中的每個元素上叫用結果選取器函式。 每個來源專案的索引會用於該專案的中繼投影形式。

SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)

將序列的每個專案投影到 IEnumerable<T>,並將產生的序列扁平化成一個序列。

SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>)

將序列的每個專案投影至 IEnumerable<T>,並將產生的序列扁平化成一個序列。 每個來源專案的索引會以該專案的投影形式使用。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T>,判斷兩個序列是否相等。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

判斷兩個序列是否相等,方法是使用其型別的默認相等比較子來比較專案。

Shuffle<TSource>(IEnumerable<TSource>)

洗牌序列中元素的順序。

Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中唯一符合指定條件的專案,如果有多個這類專案存在,則會擲回例外狀況。

Single<TSource>(IEnumerable<TSource>)

傳回序列的唯一專案,如果序列中沒有一個專案,則會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

傳回序列中唯一符合指定條件的專案,如果沒有這類專案,則傳回指定的預設值;如果一個以上的專案符合條件,這個方法會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中唯一符合指定條件的專案,如果沒有這類專案,則傳回預設值;如果一個以上的專案符合條件,這個方法會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)

傳回序列的唯一專案,如果序列是空的,則傳回指定的預設值;如果序列中有多個項目,這個方法會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的唯一專案;如果序列是空的,則傳回預設值;如果序列中有多個項目,這個方法會擲回例外狀況。

Skip<TSource>(IEnumerable<TSource>, Int32)

略過序列中指定數目的專案,然後傳回其餘專案。

SkipLast<TSource>(IEnumerable<TSource>, Int32)

回傳一個新的可枚舉集合,包含 的 source 元素,且刪除原始集合的最後元素 count

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

只要指定的條件為 true,就會略過序列中的項目,然後傳回其餘元素。

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

只要指定的條件為 true,就會略過序列中的項目,然後傳回其餘元素。 元素的索引用於述詞函式的邏輯中。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

計算 Decimal 值序列的總和,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

計算 Double 值序列的總和,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

計算 Int32 值序列的總和,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

計算 Int64 值序列的總和,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Decimal 值的序列總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Double 值的序列總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Int32 值的序列總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Int64 值的序列總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

計算在輸入序列的每個元素上叫用轉換函式所取得之可為 Null Single 值的序列總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

計算 Single 值序列的總和,這些值是在輸入序列的每個元素上叫用轉換函式所取得。

Take<TSource>(IEnumerable<TSource>, Int32)

從序列開頭傳回指定的連續項目數目。

Take<TSource>(IEnumerable<TSource>, Range)

傳回序列中連續專案的指定範圍。

TakeLast<TSource>(IEnumerable<TSource>, Int32)

回傳一個新的可枚舉集合,包含 的count最後元素source

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

只要指定的條件為 true,就會從序列傳回專案。

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

只要指定的條件為 true,就會從序列傳回專案。 元素的索引用於述詞函式的邏輯中。

ToArray<TSource>(IEnumerable<TSource>)

IEnumerable<T>建立陣列。

ToAsyncEnumerable<TSource>(IEnumerable<TSource>)

IEnumerable<T> 轉換成 IAsyncEnumerable<T>

ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式、比較子和元素選取器函式,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

根據指定的索引鍵選取器和項目選取器函式,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToFrozenDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器和項目選取器函式,從 FrozenDictionary<TKey,TValue> 建立 IEnumerable<T>

ToFrozenDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的鍵選擇函式從 FrozenDictionary<TKey,TValue> a 建立 。IEnumerable<T>

ToFrozenSet<T>(IEnumerable<T>, IEqualityComparer<T>)

建立 FrozenSet<T> 一個符合指定值的 。

ToHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

使用 HashSet<T> 比較索引鍵,從 IEnumerable<T> 建立 comparer

ToHashSet<TSource>(IEnumerable<TSource>)

HashSet<T>建立 IEnumerable<T>

ToImmutableArray<TSource>(IEnumerable<TSource>)

從指定的集合建立不可變的陣列。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>)

列舉和轉換序列,並使用指定的索引鍵和值比較子產生其內容的不可變字典。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>)

列舉和轉換序列,並使用指定的索引鍵比較子產生其內容的不可變字典。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

列舉和轉換序列,併產生其內容的不可變字典。

ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據序列的一些轉換,建構不可變的字典。

ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

從現有的專案集合建構不可變的字典,將轉換函式套用至來源索引鍵。

ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

列舉序列、產生其內容的不可變哈希集,並使用集合類型的指定相等比較子。

ToImmutableHashSet<TSource>(IEnumerable<TSource>)

列舉序列,併產生其內容的不可變哈希集。

ToImmutableList<TSource>(IEnumerable<TSource>)

列舉序列,併產生其內容的不可變清單。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>)

列舉和轉換序列,並使用指定的索引鍵和值比較子產生其內容的不可變排序字典。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>)

列舉和轉換序列,並使用指定的索引鍵比較子產生其內容的不可變排序字典。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

列舉和轉換序列,併產生其內容的不可變排序字典。

ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>)

列舉序列、產生其內容的不可變排序集,並使用指定的比較子。

ToImmutableSortedSet<TSource>(IEnumerable<TSource>)

列舉序列,併產生其內容的不可變排序集。

ToList<TSource>(IEnumerable<TSource>)

List<T>建立 IEnumerable<T>

ToLookup<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式、比較子和元素選取器函式,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

ToLookup<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

根據指定的索引鍵選取器和項目選取器函式,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

ToLookup<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

ToLookup<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

TryGetNonEnumeratedCount<TSource>(IEnumerable<TSource>, Int32)

嘗試判斷序列中的元素數目,而不強制列舉。

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T>產生兩個序列的集合聯集。

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子產生兩個序列的集合聯集。

UnionBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合聯集。

UnionBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合聯集。

Where<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

根據述詞篩選值序列。

Where<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

根據述詞篩選值序列。 每個元素的索引都會用於述詞函式的邏輯中。

Zip<TFirst,TSecond,TResult>(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst,TSecond,TResult>)

將指定的函式套用至兩個序列的對應專案,產生結果序列。

Zip<TFirst,TSecond,TThird>(IEnumerable<TFirst>, IEnumerable<TSecond>, IEnumerable<TThird>)

產生具有來自三個指定序列之元素的 Tuple 序列。

Zip<TFirst,TSecond>(IEnumerable<TFirst>, IEnumerable<TSecond>)

產生具有來自兩個指定序列之元素的 Tuple 序列。

適用於

執行緒安全性

此類型是安全線程。

另請參閱