共用方式為


比較和排序特定文化特性的資料

排序和排序資料的慣例與文化特性而異的文化特性。 例如,排序次序可以是區分大小寫或者不區分大小寫。 它可能語音數學或根據字元的視覺化表示。 在東亞語系中,排序次序可依筆劃和文字字根進行。 排序也是根據命令語言和文化特性使用字母的。 例如,丹麥文的 "Æ" 字元的字母排列在 "Z" 之後。 為支援特定文化特性和特性語言排序慣例,世界性的應用程式必須能夠根據個別的文化特性來比較和排序資料。

注意事項注意事項

在有些案例中,並不適合區分文化特性的行為。如需執行不區分文化特性作業之時機和方式的詳細資訊,請參閱不區分文化特性的字串作業

比較字串

CompareInfo 類別提供可用來執行區分文化特性字串比較的方法集。 CultureInfo 類別有 CompareInfo 屬性,這是此類別CompareInfo的執行個體。 CompareInfo這個屬性定義比較和排序特定文化特性字串的方法。 String.Compare 方法在文化特性的物件 CompareInfo 使用資訊來比較字串。

下列範例示範根據用來比較的文化特性 String.Compare 說明方法如何以不同方式評估兩個字串 (「Apple」和「Æble」)。 首先, System.Threading.Thread.CurrentThread.CurrentCulture 屬性會設為丹麥文 (丹麥) 文化特性的 da-DK。 丹麥文會將字元 "Æ" 視為單一字母,其字母排列位於字母 "Z" 之後。 因此,比「Apple」判斷字串「Æble」大於丹麥文 (丹麥) 文化特性的。 接著, System.Threading.Thread.CurrentThread.CurrentCulture 屬性設為英文 (美國) 文化特性的 en-US,英文會將字元「Æ」視為特殊符號並在字母「A」之前。 因此,英文 (美國) 文化特性的判斷字串「Apple」小於「Æble」。

Imports System.Globalization
Imports System.Threading

Public Class TestClass
   Public Shared Sub Main()
      Dim str1 As String = "Apple"
      Dim str2 As String = "Æble"

      ' Set the current culture to Danish in Denmark.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("da-DK")
      Dim result1 As Integer = [String].Compare(str1, str2)
      Console.WriteLine("When the CurrentCulture is ""da-DK"",")
      Console.WriteLine("the result of comparing_{0} with {1} is: {2}", 
                        str1, str2, result1)

      ' Set the current culture to English in the U.S.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      Dim result2 As Integer = [String].Compare(str1, str2)
      Console.WriteLine("When the CurrentCulture is""en-US"",")
      Console.WriteLine("the result of comparing {0} with {1} is: {2}", 
                        str1, str2,result2)
   End Sub
End Class
' The example displays the following output:
'    When the CurrentCulture is "da-DK",
'    the result of comparing Apple with Æble is: -1
'    
'    When the CurrentCulture is "en-US",
'    the result of comparing Apple with Æble is: 1
using System;
using System.Globalization;
using System.Threading;

public class CompareStringSample
{
   public static void Main()
   {
      string str1 = "Apple";
      string str2 = "Æble"; 

      // Sets the CurrentCulture to Danish in Denmark.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
      // Compares the two strings.
      int result1 = String.Compare(str1, str2);
      Console.WriteLine("\nWhen the CurrentCulture is \"da-DK\",\nthe " + 
                        "result of comparing {0} with {1} is: {2}", str1, str2, 
                        result1);

      // Sets the CurrentCulture to English in the U.S.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      // Compares the two strings.
      int result2 = String.Compare(str1, str2);
      Console.WriteLine("\nWhen the CurrentCulture is \"en-US\",\nthe " + 
                        "result of comparing {0} with {1} is: {2}", str1, str2, 
                        result2);
   }
}
// The example displays the following output:
//    When the CurrentCulture is "da-DK",
//    the result of comparing Apple with Æble is: -1
//    
//    When the CurrentCulture is "en-US",
//    the result of comparing Apple with Æble is: 1

如需比較字串的詳細資訊,請參閱 比較字串。

使用替代排序次序

有些文化特性支援一個以上的排序次序。 例如,為 zh-CN 中文 (中華人民共和國) 文化特性支援兩個排序順序: 使用拼音 (預設值) 和由筆畫。 當您的應用程式使用文化特性名稱 (例如 "zh-CN") 建立 CultureInfo 物件時,將使用預設的排序次序。 如果要指定替代排序次序,請呼叫 CultureInfo.CultureInfo(Int32) 或 CultureInfo.CultureInfo(Int32, Boolean) 建構函式和使用識別項來建構物件 CultureInfo 替代排序次序,然後從衍生 CompareInfo 屬性的 CompareInfo 物件所使用的字串比較。 或者,您的應用程式也可以直接使用 CompareInfo.GetCompareInfo 方法建立 CompareInfo 物件,指定識別項做為替代的排序次序。

下表列出支援替代排序次序的文化特性清單,以及預設和替代排序次序的識別項。

文化特性名稱

文化特性

預設的排序名稱和識別項

替代排序名稱和識別項

es-ES

西班牙文 (西班牙)

國際:0x00000C0A

傳統:0x0000040A

zh-TW

中文 (台灣)

筆劃:0x00000404

注音符號:0x00030404

zh-CN

中文 (中華人民共和國)

發音:0x00000804

筆劃:0x00020804

zh-HK

中文 (香港特別行政區)

發音:0x00000c04

筆劃:0x00020c04

zh-SG

中文 (新加坡)

發音:0x00001004

筆劃:0x00021004

zh-MO

中文 (澳門特別行政區)

發音:0x00001404

筆劃:0x00021404

ja-JP

日文 (日本)

預設:0x00000411

Unicode:0x00010411

ko-KR

韓文 (韓國)

預設:0x00000412

韓文 Xwansung - Unicode:0x00010412

de-DE

德文 (德國)

字典:0x00000407

電話簿排序 DIN:0x00010407

hu-HU

匈牙利文 (匈牙利)

預設:0x0000040e

技術排序:0x0001040e

ka-GE

喬治亞文 (喬治亞)

傳統:0x00000437

西班牙現代排序:0x00010437

搜尋字串

您的應用程式可以使用多載的 CompareInfo.IndexOf 方法以零起始索引來擷取指定字串中字元或子字串。 如果沒有找到,則方法會傳回-1 個字元或子字串。 在搜尋指定的字元時, IndexOf 接受的多載型別 CompareOptions 參數可能執行比較與不接受這個參數的方法多載不同。 沒有這個參數的方法多載會執行區分文化特性,區分大小寫的搜尋。 這表示如果 Unicode 值代表的是預先組成的字元,例如連字 "Æ" (\u00C6),視文化特性而定,只要其組成元件以正確序列出現,就可能視為相等,例如 "AE" (\u0041\u0045)。 若要執行序數 (不區分文化特性) 搜尋確切的 Unicode 值,請使用接受型別 CompareOptions 參數並將參數設為Ordinal 的其中一 CompareInfo.IndexOf 多載。

您的應用程式也可以使用搜尋字元的 String.IndexOf 方法多載來執行序數 (不區分文化特性) 搜尋。 請注意,此方法搜尋字串的多載會執行區分文化特性的搜尋。

下列程式碼範例示範根據文化特性,CompareInfo.IndexOf 方法擷取的不同結果。 這個範例會建立一 CultureInfo 物件為丹麥文 (丹麥) 和英文 (美國) 文化 CompareInfo.IndexOf 和使用方法的多載中搜尋字元「æ」中的「aeble」的字串和「æble」。 對於丹麥文 (丹麥) 文化特性、 CompareInfo.IndexOf(String, Char) 方法和具有 CompareOptions.Ordinal 傳回比較選項各字串的相同值的 CompareInfo.IndexOf(String, Char, CompareOptions) 方法。 這表示字元「æ」視為只等同於 Unicode 值\ u00E6。 對於英文 (美國) 文化特性,兩個多載會傳回不同的結果,在搜尋「æ」中的「aeble」中的字串。 由 CompareInfo.IndexOf(String, Char) 方法執行的區分文化特性比較,會將字元 "æ" 評估為與其元件 "a" 和 "e" 完全相同。

Imports System.Globalization
Imports System.Threading

Public Class Example
   Public Shared Sub Main()
      Dim str1 As String = "æble"
      Dim str2 As String = "aeble"
      Dim find As Char = "æ"c

      ' Create CultureInfo objects representing the Danish (Denmark)
      ' and English (United States) cultures.
      Dim cultures() As CultureInfo = { CultureInfo.CreateSpecificCulture("da-DK"), 
                                        CultureInfo.CreateSpecificCulture("en-US") }

      For Each ci In cultures
         Thread.CurrentThread.CurrentCulture = ci

         Dim result1 As Integer = ci.CompareInfo.IndexOf(str1, find)
         Dim result2 As Integer = ci.CompareInfo.IndexOf(str2, find)
         Dim result3 As Integer = ci.CompareInfo.IndexOf(str1, find, _ 
            CompareOptions.Ordinal)
         Dim result4 As Integer = ci.CompareInfo.IndexOf(str2, find, _
            CompareOptions.Ordinal)      

         Console.WriteLine("The current culture is {0}", 
                           CultureInfo.CurrentCulture.Name)
         Console.WriteLine()
         Console.WriteLine("   CompareInfo.IndexOf(string, char) method:")
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str1, result1)
         Console.WriteLine()
         Console.WriteLine("   CompareInfo.IndexOf(string, char) method:")
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str2, result2)
         Console.WriteLine()
         Console.WriteLine("   CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method")
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str1, result3)
         Console.WriteLine()
         Console.WriteLine("   CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method")
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str2, result4)
         Console.WriteLine()
      Next
   End Sub
End Class
' The example displays the following output:
'    The current culture is da-DK
'    
'       CompareInfo.IndexOf(string, char) method:
'       Position of æ in the string æble: 0
'    
'       CompareInfo.IndexOf(string, char) method:
'       Position of æ in the string aeble: -1
'    
'       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
'       Position of æ in the string æble: 0
'    
'       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
'       Position of æ in the string aeble: -1
'    
'    The current culture is en-US
'    
'       CompareInfo.IndexOf(string, char) method:
'       Position of æ in the string æble: 0
'    
'       CompareInfo.IndexOf(string, char) method:
'       Position of æ in the string aeble: 0
'    
'       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
'       Position of æ in the string æble: 0
'    
'       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
'       Position of æ in the string aeble: -1
using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      string str1 = "æble";
      string str2 = "aeble";
      char find = 'æ';

      // Create CultureInfo objects representing the Danish (Denmark)
      // and English (United States) cultures.
      CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("da-DK"), 
                                 CultureInfo.CreateSpecificCulture("en-US") };

      foreach (var ci in cultures) {
         Thread.CurrentThread.CurrentCulture = ci;

         int result1 = ci.CompareInfo.IndexOf(str1, find);
         int result2 = ci.CompareInfo.IndexOf(str2, find);
         int result3 = ci.CompareInfo.IndexOf(str1, find,  
                                              CompareOptions.Ordinal);
         int result4 = ci.CompareInfo.IndexOf(str2, find, 
                                              CompareOptions.Ordinal);      

         Console.WriteLine("\nThe current culture is {0}", 
                           CultureInfo.CurrentCulture.Name);
         Console.WriteLine("\n   CompareInfo.IndexOf(string, char) method:");
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str1, result1);

         Console.WriteLine("\n   CompareInfo.IndexOf(string, char) method:");
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str2, result2);

         Console.WriteLine("\n   CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method");
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str1, result3);

         Console.WriteLine("\n   CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method");
         Console.WriteLine("   Position of {0} in the string {1}: {2}", 
                           find, str2, result4);
         Console.WriteLine();
      }   
   }
}
// The example displays the following output
//    The current culture is da-DK
//    
//       CompareInfo.IndexOf(string, char) method:
//       Position of æ in the string æble: 0
//    
//       CompareInfo.IndexOf(string, char) method:
//       Position of æ in the string aeble: -1
//    
//       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
//       Position of æ in the string æble: 0
//    
//       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
//       Position of æ in the string aeble: -1
//    
//    
//    The current culture is en-US
//    
//       CompareInfo.IndexOf(string, char) method:
//       Position of æ in the string æble: 0
//    
//       CompareInfo.IndexOf(string, char) method:
//       Position of æ in the string aeble: 0
//    
//       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
//       Position of æ in the string æble: 0
//    
//       CompareInfo.IndexOf(string, char, CompareOptions.Ordinal) method
//       Position of æ in the string aeble: -1

排序字串

您可以使用特定 Array.Sort 方法的多載以目前文化特性的陣列。 在下列範例中,將建立由三個字串組成的陣列。 首先,它會將屬性設定為 System.Threading.Thread.CurrentThread.CurrentCulture en-US Array.Sort(Array) 並呼叫方法。 產生的排序次序將使用英文 (美國) 文化特性的排序慣例做為依據。 接著,此範例會 System.Threading.Thread.CurrentThread.CurrentCulture 屬性設為 da-DK Array.Sort 並再次呼叫方法。 由於使用的是 da-DK 文化特性的排序慣例,因此請注意產生的排序次序與 en-US 結果有何不同之處。

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
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

使用排序鍵

.NET Framework 使用排序鍵支援區分文化特性的排序作業。 字串中各個字元都被賦予數個分類的排序權重,包括指令碼、字母順序、大小寫和變音符號權重。 排序鍵可以當做特定字串的這些權重的存放庫。 例如,排序鍵可能含有字母權重字串,之後跟隨大小寫權重字串,等等。 如需排序鍵的詳細資訊,請參閱 <Unicode Technical Standard #10:Unicode 排序演算法> 的Unicode標準。

在 .NET Framework 中, SortKey 類別將字串對應到其排序鍵。 您的應用程式可以使用 CompareInfo.GetSortKey 方法為您指定的字串建立排序鍵。 結果可以是不同的位元組序列根據指定的 CurrentCulture 屬性和 CompareOptions 值。 例如,如果您指定 CompareOptions.IgnoreCase值 ,在建立排序鍵時,使用排序鍵的字串比較作業不區分大小寫。

在建立字串的第二個排序鍵,您可以將它或者參數傳遞至提供的方法 SortKey 類別。 SortKey.Compare 方法可讓您比較排序鍵。 由於這個方法會執行簡單的位元組逐一比較,因此速度要比使用 String.Compare 快得多。 如果您的應用程式執行大量排序作業,您可以產生並儲存它所使用的任何字串的排序鍵可改善其效能。 如果需要使用排序或比較作業,應用程式就可以使用排序鍵,而不是字串。

下列程式碼範例會在CurrentCulture設為 da-DK 時建立兩個字串 (str1 和 str2) 的排序鍵。 它將使用 SortKey.Compare 方法來比較這兩個字串,並且顯示其結果。 如果 str2 小於 str1,str1 方法將傳回負整數,如果 str2 和 str1 相等,將傳回零 (0),如果 str2 大於 ,將傳回正整數。 接下來,範例會將屬性設定為 System.Threading.Thread.CurrentThread.CurrentCulture en-US 並建立相同字串的排序鍵。 這個範例會比較排序鍵並顯示結果。 請注意以目前文化特性的設定排序結果不同。 雖然下列範例的結果和這個主題稍早出現的比較字串範例結果完全相同,但是使用 SortKey.Compare 方法比使用 String.Compare 方法的速度更快。

Imports System.Globalization
Imports System.Threading

Public Class SortKeySample
   Public Shared Sub Main()
      Dim str1 As [String] = "Apple"
      Dim str2 As [String] = "Æble"

      ' Set the CurrentCulture to "da-DK".
      Dim dk As New CultureInfo("da-DK")
      Thread.CurrentThread.CurrentCulture = dk

      ' Create a culturally sensitive sort key for str1.
      Dim sc1 As SortKey = dk.CompareInfo.GetSortKey(str1)
      ' Create a culturally sensitive sort key for str2.
      Dim sc2 As SortKey = dk.CompareInfo.GetSortKey(str2)

      ' Compare the two sort keys and display the results.
      Dim result1 As Integer = SortKey.Compare(sc1, sc2)
      Console.WriteLine("When the  current culture is ""da-DK"",")
      Console.WriteLine("the result of comparing {0} with {1} is: {2}", 
                        str1, str2, result1)
      Console.WriteLine()

      ' Set the CurrentCulture to "en-US".
      Dim enus As New CultureInfo("en-US")
      Thread.CurrentThread.CurrentCulture = enus

      ' Create a culturally sensitive sort key for str1.
      Dim sc3 As SortKey = enus.CompareInfo.GetSortKey(str1)
      ' Create a culturally sensitive sort key for str1.
      Dim sc4 As SortKey = enus.CompareInfo.GetSortKey(str2)

      ' Compare the two sort keys and display the results.
      Dim result2 As Integer = SortKey.Compare(sc3, sc4)
      Console.WriteLine("When the CurrentCulture is ""en-US"",")
      Console.WriteLine("the result of comparing {0} with {1} is: {2}", 
                        str1, str2, result2)
   End Sub
End Class
' The example displays the following output:
'       When the  current culture is "da-DK",
'       the result of comparing Apple with Æble is: -1
'       
'       When the CurrentCulture is "en-US",
'       the result of comparing Apple with Æble is: 1
using System;
using System.Threading;
using System.Globalization;

public class SortKeySample 
{
   public static void Main(String[] args) 
   {
      String str1 = "Apple";
      String str2 = "Æble";

      // Set the CurrentCulture to "da-DK".
      CultureInfo dk = new CultureInfo("da-DK");
      Thread.CurrentThread.CurrentCulture = dk;

      // Create a culturally sensitive sort key for str1.
      SortKey sc1 = dk.CompareInfo.GetSortKey(str1);
      // Create a culturally sensitive sort key for str2.
      SortKey sc2 = dk.CompareInfo.GetSortKey(str2);

      // Compare the two sort keys and display the results.
      int result1 = SortKey.Compare(sc1, sc2);
      Console.WriteLine("When the CurrentCulture is \"da-DK\",");
      Console.WriteLine("the result of comparing {0} with {1} is: {2}\n", 
                        str1, str2, result1);

      // Set the CurrentCulture to "en-US".
      CultureInfo enus = new CultureInfo("en-US");
      Thread.CurrentThread.CurrentCulture = enus ;

      // Create a culturally sensitive sort key for str1.
      SortKey sc3 = enus.CompareInfo.GetSortKey(str1);
      // Create a culturally sensitive sort key for str1.
      SortKey sc4 = enus.CompareInfo.GetSortKey(str2);

      // Compare the two sort keys and display the results.
      int result2 = SortKey.Compare(sc3, sc4);
      Console.WriteLine("When the CurrentCulture is \"en-US\",");
      Console.WriteLine("the result of comparing {0} with {1} is: {2}", 
                        str1, str2, result2);
   }
}
// The example displays the following output:
//       When the CurrentCulture is "da-DK",
//       the result of comparing Apple with Æble is: -1
//       
//       When the CurrentCulture is "en-US",
//       the result of comparing Apple with Æble is: 1

正規化

您可以標準化為大寫或小寫再排序它們。 大小寫和字串的排序為語言特定規則,即使在拉丁指令碼架構語言內變更。 只有少數的語言 (包括英文) 的排序次序是與字碼指標的次序相符,例如 A [65] 在 B [66] 之前。 因此,請不要依賴字碼指標來執行精準的排序和比較字串。

.NET Framework 可支援所有 Unicode 正規化型態且並不會強制執行或保證正規化特定形態。 您必須負責選取應用程式的適當正規化。

如需字串正規化的詳細資訊,請參閱 String 類別主題中的 < 正規化 > 一節。

請參閱

概念

不區分文化特性的字串作業

其他資源

全球化和當地語系化 .NET Framework 應用程式