String.Compare 方法 (String, String, Boolean)
組件: mscorlib (在 mscorlib.dll 中)
比較過程會使用目前的文化特性取得文化特性的特定資訊,例如大小寫規則和個別字元的字母順序。例如,文化特性可能會指定字元的特定組合需視為單一字元、大寫及小寫字元要以特定方式加以比較,或者排序順序要根據其前後的字元等。
比較過程會使用文字排序規則執行。如需文字、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions。
其中一個或兩個比較元都可以是 Null 參照 (即 Visual Basic 中的 Nothing)。根據定義,任何包括空字串 ("") 在內的字串,都比 Null 參考大;而兩個 Null 參考則彼此相等。
當發現有不等或兩個字串都比較過之後,比較則會結束。然而,比較兩個字串時,如果比較至其中一個字串的結尾都是相等的,但另一個字串還有多餘的字元,那麼具有多餘字元的字串將被視為較大。傳回值是上次所執行之比較的結果。
當比較過程會受文化特性的特定大小寫規則影響時,即可能發生未預期的結果。例如,就土耳其文而言,下列範例會產生錯誤結果;因為土耳其文的檔案系統對於 "file" 中的字母 'i' 並不使用語言上的大小寫規則。
static String IsFileURI(String path) {
return (String.Compare(path, 0, "file:", 0, 5, true)== 0); }
使用序數比較,將路徑名稱比做「檔案」。執行這種作業的正確程式碼如下所示:
static String IsFileURI(String path) {
return (String.Compare(path, 0, "file:", 0, 5, true, StringComparison.OrdinalIgnoreCase)== 0); }
下列程式碼範例說明了在比對字串時,如何將使用 Compare 方法與使用 ToUpper 或 ToLower 產生相同的效果。
unsafe { // Null terminated ASCII characters in an sbyte array String szAsciiUpper = null; sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 }; // Instruct the Garbage Collector not to move the memory fixed(sbyte* pAsciiUpper = sbArr1) { szAsciiUpper = new String(pAsciiUpper); } String szAsciiLower = null; sbyte[] sbArr2 = { 0x61, 0x62, 0x63, 0x00 }; // Instruct the Garbage Collector not to move the memory fixed(sbyte* pAsciiLower = sbArr2) { szAsciiLower = new String(pAsciiLower, 0, sbArr2.Length); } // Prints "ABC abc" Console.WriteLine(szAsciiUpper + " " + szAsciiLower); // Compare Strings - the result is true Console.WriteLine("The Strings are equal when capitalized ? " + (String.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper())==0?"true":"false") ); // This is the effective equivalent of another Compare method, which ignores case Console.WriteLine("The Strings are equal when capitalized ? " + (String.Compare(szAsciiUpper, szAsciiLower, true)==0?"true":"false") ); }
Windows 98、 Windows 2000 SP4、 Windows CE、 Windows Millennium Edition、 Windows Mobile for Pocket PC、 Windows Mobile for Smartphone、 Windows Server 2003、 Windows XP Media Center Edition、 Windows XP Professional x64 Edition、 Windows XP SP2、 Windows XP Starter Edition
.NET Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱系統需求一節的內容。
