String String String String Class

定义

将文本表示为 UTF-16 代码单元的序列。 Represents text as a sequence of UTF-16 code units.

public ref class String sealed : ICloneable, IComparable, IComparable<System::String ^>, IConvertible, IEquatable<System::String ^>, System::Collections::Generic::IEnumerable<char>
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class String : ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
type string = class
    interface IComparable
    interface ICloneable
    interface IConvertible
    interface IEnumerable
    interface IComparable<string>
    interface seq<char>
    interface IEquatable<string>
Public NotInheritable Class String
Implements ICloneable, IComparable, IComparable(Of String), IConvertible, IEnumerable(Of Char), IEquatable(Of String)
继承
StringStringStringString
属性
ComVisibleAttribute SerializableAttribute
实现

注解

字符串是用于表示文本字符的序列集合。A string is a sequential collection of characters that is used to represent text. 一个String对象是的有序集合System.Char这些对象表示一个字符串;System.Char对象对应于 utf-16 代码单元。A String object is a sequential collection of System.Char objects that represent a string; a System.Char object corresponds to a UTF-16 code unit. String对象为的有序集合的内容System.Char对象和值是不可变 (即,它是只读的)。The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only). 字符串的不可变性的详细信息,请参阅不变性和 StringBuilder 类本主题后面的部分。For more information about the immutability of strings, see the Immutability and the StringBuilder class section later in this topic. 最大大小String对象在内存中的为 2 GB 或大约 1 亿个字符。The maximum size of a String object in memory is 2GB, or about 1 billion characters.

本节内容:In this section:

实例化字符串对象 Instantiating a String object
Char 对象和 Unicode 字符 Char objects and Unicode characters
字符串和 Unicode 标准 Strings and The Unicode Standard
字符串和嵌入的 null 字符 Strings and embedded null characters
字符串和已分区索引 Strings and indexes
Null 字符串和空字符串 Null strings and empty strings
不变性和 StringBuilder 类 Immutability and the StringBuilder class
区分区域性的操作与序号 Ordinal vs. culture-sensitive operations
规范化 Normalization
按类别的字符串操作String operations by category

实例化字符串对象Instantiating a String object

可以实例化String对象中的以下方法:You can instantiate a String object in the following ways:

  • 通过将分配一个字符串赋给String变量。By assigning a string literal to a String variable. 这是用于创建一个字符串,最常使用的方法。This is the most commonly used method for creating a string. 下面的示例使用分配来创建多个字符串。The following example uses assignment to create several strings. 请注意,在 C# 中,因为反斜杠 (\) 是转义的字符,在字符串中的文本反斜杠必须进行转义或者整个字符串必须是@-quoted。Note that in C#, because the backslash (\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted.

    using namespace System;
    
    void main()
    {
       String^ string1 = "This is a string created by assignment.";
       Console::WriteLine(string1);
       String^ string2a = "The path is C:\\PublicDocuments\\Report1.doc";
       Console::WriteLine(string2a);
    }
    // The example displays the following output: 
    //       This is a string created by assignment. 
    //       The path is C:\PublicDocuments\Report1.doc 
    
    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      
    
    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      
    
  • 通过调用String类构造函数。By calling a String class constructor. 下面的示例通过调用多个类构造函数实例化字符串。The following example instantiates strings by calling several class constructors. 请注意,一些构造函数包含指向字符数组或作为参数的有符号的字节数组的指针。Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic 不支持对这些构造函数的调用。Visual Basic does not support calls to these constructors. 有关详细信息String构造函数,请参阅String摘要的构造函数。For detailed information about String constructors, see the String constructor summary.

    using namespace System;
    
    void main()
    {
       wchar_t chars[5] = L"word";
       char bytes[6] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
    
       // Create a string from a character array. 
       String^ string1 = gcnew String(chars);
       Console::WriteLine(string1);
    
       // Create a string that consists of a character repeated 20 times. 
       String^ string2 = gcnew String('c', 20);
       Console::WriteLine(string2);
    
       String^ stringFromBytes = nullptr;
       String^ stringFromChars = nullptr;
    
       char * pbytes = &bytes[0];
       // Create a string from a pointer to a signed byte array.
       stringFromBytes = gcnew String(pbytes);
    
       wchar_t* pchars =  &chars[0];
       // Create a string from a pointer to a character array.
       stringFromChars = gcnew String(pchars);
    
       Console::WriteLine(stringFromBytes);
       Console::WriteLine(stringFromChars);
       Console::ReadLine();
    }
    // The example displays the following output: 
    //       word 
    //       cccccccccccccccccccc 
    //       ABCDE 
    //       word  
    
    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  
    
    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# 中和 (& a) 或 + 在 Visual Basic 中) 中的任意组合创建单个字符串String实例和字符串文本。By using the string concatenation operator (+ in C# and & or + in Visual Basic) to create a single string from any combination of String instances and string literals. 下面的示例演示如何使用字符串串联运算符。The following example illustrates the use of the string concatenation operator.

    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.
    
    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.
    
    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.
    
  • 通过检索属性或调用返回的字符串的方法。By retrieving a property or calling a method that returns a string. 下面的示例使用的方法String类,以从更大的字符串中提取子字符串。The following example uses the methods of the String class to extract a substring from a larger 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);
    
    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
    
    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
    
  • 通过调用将的值或对象转换为其字符串表示形式的格式设置方法。By calling a formatting method to convert a value or object to its string representation. 下面的示例使用复合格式设置功能嵌入的两个对象的字符串表示形式转换为字符串。The following example uses the composite formatting feature to embed the string representation of two objects into a string.

    DateTime^ dateAndTime = gcnew 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.      
    
    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.      
    
    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 字符Char objects and Unicode characters

在字符串中的每个字符由 Unicode 标量值,也称为 Unicode 码位或序号 (数字) 值的 Unicode 字符的定义。Each character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. 每个码位编码使用 utf-16 编码,并且由表示编码的每个元素的数值Char对象。Each code point is encoded by using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.

备注

注意,因为String实例都包含 utf-16 代码单元的有序集合,可以将创建String不是格式正确的 Unicode 字符串的对象。Note that, because a String instance consists of a sequential collection of UTF-16 code units, it is possible to create a String object that is not a well-formed Unicode string. 例如,就可以创建具有低代理项而无需相应的高代理项的字符串。For example, it is possible to create a string that has a low surrogate without a corresponding high surrogate. 尽管某些方法,如编码和解码中的对象的方法System.Text命名空间,可能会执行检查,以确保字符串格式不正确,String类成员不能确保字符串是格式正确。Although some methods, such as the methods of encoding and decoding objects in the System.Text namespace, may performs checks to ensure that strings are well-formed, String class members don't ensure that a string is well-formed.

将单个Char对象通常表示单个码位; 也就是说的数值Char等于码位。A single Char object usually represents a single code point; that is, the numeric value of the Char equals the code point. 例如,码位的字符"a"为 U + 0061。For example, the code point for the character "a" is U+0061. 但是,代码点可能需要多个编码的元素 (多个Char对象)。However, a code point might require more than one encoded element (more than one Char object). Unicode 标准定义了两种类型的相对应的字符到多个Char对象: graphemes,并对应于在 Unicode 辅助平面字符的 Unicode 补充码位。The Unicode standard defines two types of characters that correspond to multiple Char objects: graphemes, and Unicode supplementary code points that correspond to characters in the Unicode supplementary planes.

  • 表示基字符后跟一个或多个组合字符字形。A grapheme is represented by a base character followed by one or more combining characters. 例如,由一个表示字符 äChar对象,其代码点为 U + 0061 跟一个Char对象,其代码点为 U + 0308年。For example, the character ä is represented by a Char object whose code point is U+0061 followed by a Char object whose code point is U+0308. 此字符也可以定义由单个Char具有码位 U + 00E4 的对象。This character can also be defined by a single Char object that has a code point of U+00E4. 如下面的示例所示,需要区分区域性的比较相等性指示这两种表示相等,尽管普通的序号比较则不然。As the following example shows, a culture-sensitive comparison for equality indicates that these two representations are equal, although an ordinary ordinal comparison does not. 但是,如果两个字符串进行规范化,序号比较还指示它们是否相等。However, if the two strings are normalized, an ordinal comparison also indicates that they are equal. (有关规范化字符串的详细信息,请参阅规范化部分。)(For more information on normalizing strings, see the Normalization section.)

    using namespace System;
    using namespace System::Globalization;
    using namespace System::IO;
    
    void main()
    {
       StreamWriter^ sw = gcnew StreamWriter(".\\graphemes.txt");
       String^ grapheme = L"a" + L"\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
    
    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
    
    Imports System.Globalization
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\graphemes.txt")
          Dim grapheme As String = ChrW(&H0061) + ChrW(&h0308)
          sw.WriteLine(grapheme)
          
          Dim singleChar As String = ChrW(&h00e4)
          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
    
  • 补充码位 (代理项对) 表示的 UnicodeChar对象,其码位是一个高代理项跟Char对象,其码位是一个低代理项。A Unicode supplementary code point (a surrogate pair) is represented by a Char object whose code point is a high surrogate followed by a Char object whose code point is a low surrogate. 高代理项范围从 u+d800 到 U + DBFF 代码单元。The code units of high surrogates range from U+D800 to U+DBFF. 低代理项范围是从 U+DC00 到 U + DFFF 代码单元。The code units of low surrogates range from U+DC00 to U+DFFF. 代理项对用于表示中 16 Unicode 辅助平面字符。Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. 以下示例创建一个代理项字符并将其传递给Char.IsSurrogatePair(Char, Char)方法以确定它是否是代理项对。The following example creates a surrogate character and passes it to the Char.IsSurrogatePair(Char, Char) method to determine whether it is a surrogate pair.

    using namespace System;
    
    void main()
    {
       String^ surrogate =  L"\xD800\xDC03" ;
       for (int ctr = 0; ctr < surrogate->Length; ctr++)
          Console::Write("U+{0:X4} ", Convert::ToUInt16(surrogate[ctr]));
    
       Console::WriteLine();
       Console::WriteLine("   Is Surrogate Pair: {0}", 
                          Char::IsSurrogatePair(surrogate[0], surrogate[1]));
       Console::ReadLine();
    }
    // The example displays the following output: 
    //       U+D800 U+DC03 
    //          Is Surrogate Pair: True
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          string surrogate = "\uD800\uDC03";
          for (int ctr = 0; ctr < surrogate.Length; ctr++) 
             Console.Write("U+{0:X2} ", Convert.ToUInt16(surrogate[ctr]));
    
          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
    
    Module Example
       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 标准Strings and the Unicode Standard

字符串中的字符都是 utf-16 编码代码单元,它们分别对应于Char值。Characters in a string are represented by UTF-16 encoded code units, which correspond to Char values.

在字符串中的每个字符包含在.NET 中的关联的 Unicode 字符类别UnicodeCategory枚举。Each character in a string has an associated Unicode character category, which is represented in .NET by the UnicodeCategory enumeration. 可通过调用确定的字符或代理项对类别CharUnicodeInfo.GetUnicodeCategory方法。The category of a character or a surrogate pair can be determined by calling the CharUnicodeInfo.GetUnicodeCategory method.

.NET 维护自己的字符表及其相应的类别,这可确保在不同平台上运行的特定版本的 .NET 实现返回相同的字符类别信息。.NET maintains its own table of characters and their corresponding categories, which ensures that a specific version of a .NET implementation running on different platforms returns identical character category information. Linux 和 macOS 上运行的 .NET Core 上,字符类别信息由 Unicode 国际组件库提供。On .NET Core running on Linux and macOS, character category information is provided by International Components for Unicode libraries.

下表列出了 .NET 版本及其字符类别所基于的 Unicode 标准。The following table lists .NET versions and the versions of the Unicode Standard on which their character categories are based.

.NET 版本.NET version Unicode 标准版本Version of the Unicode Standard
.NET Framework 1.1.NET Framework 1.1 Unicode 标准,版本 4.0.0The Unicode Standard, Version 4.0.0
.NET Framework 2.0.NET Framework 2.0 Unicode 标准,版本 5.0.0The Unicode Standard, Version 5.0.0
.NET Framework 3.5.NET Framework 3.5 Unicode 标准,版本 5.0.0The Unicode Standard, Version 5.0.0
.NET Framework 4.NET Framework 4 Unicode 标准,版本 5.0.0The Unicode Standard, Version 5.0.0
.NET Framework 4.5.NET Framework 4.5 Unicode 标准,版本 6.3.0The Unicode Standard, Version 6.3.0
.NET Framework 4.51.NET Framework 4.51 Unicode 标准,版本 6.3.0The Unicode Standard, Version 6.3.0
.NET Framework 4.52.NET Framework 4.52 Unicode 标准,版本 6.3.0The Unicode Standard, Version 6.3.0
.NET Framework 4.6.NET Framework 4.6 Unicode 标准,版本 6.3.0The Unicode Standard, Version 6.3.0
.NET Framework 4.61.NET Framework 4.61 Unicode 标准,版本 6.3.0The Unicode Standard, Version 6.3.0
.NET Framework 4.6.2 及更高版本.NET Framework 4.6.2 and later versions Unicode 标准,版本 8.0.0The Unicode Standard, Version 8.0.0
.NET Core(所有版本).NET Core (all versions) Unicode 标准,版本 8.0.0The Unicode Standard, Version 8.0.0

此外,.NET 支持的字符串比较和排序基于 Unicode 标准。In addition, .NET supports string comparison and sorting based on the Unicode standard. 通过.NET Framework 的版本中.NET Framework 4.NET Framework 4,.NET Framework 维护自己的字符串数据的表。In versions of the .NET Framework through the .NET Framework 4.NET Framework 4, the .NET Framework maintains its own table of string data. 这也是如此的开头的.NET framework 版本.NET Framework 4.5.NET Framework 4.5Windows 7 上运行。This is also true of versions of the .NET Framework starting with the .NET Framework 4.5.NET Framework 4.5 running on Windows 7. 从开始.NET Framework 4.5.NET Framework 4.5Window 8 和更高版本的 Windows 操作系统上运行,运行时委托字符串比较和排序操作对操作系统。Starting with the .NET Framework 4.5.NET Framework 4.5 running on Window 8 and later versions of the Windows operating system, the runtime delegates string comparison and sorting operations to the operating system. 在.NET Core 上的字符串比较和排序信息将由International Components for Unicode库。下表列出了版本的.NET 和 Unicode 标准的字符的比较和排序所基于的版本。On .NET Core, string comparison and sorting information is provided by International Components for Unicode libraries.The following table lists the versions of .NET and the versions of the Unicode Standard on which character comparison and sorting are based.

.NET 版本.NET version Unicode 标准版本Version of the Unicode Standard
.NET Framework 1.1.NET Framework 1.1 Unicode 标准版本 4.0.0The Unicode Standard, Version 4.0.0
.NET Framework 2.0The .NET Framework 2.0 Unicode 标准,5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 3.5.NET Framework 3.5 Unicode 标准,5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.NET Framework 4 Unicode 标准,5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.5.NET Framework 4.5 和更高版本在 Windows 7and later on Windows 7 Unicode 标准,5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.5.NET Framework 4.5 和更高版本在 Windows 8 和更高版本的 Windows 操作系统and later on Windows 8 and later Windows operating systems Unicode 标准 6.3.0 版The Unicode Standard, Version 6.3.0
.NET core (所有版本).NET Core (all versions) 取决于基础操作系统支持的 Unicode 标准版本。Depends on the version of hte Unicode Standard supported by the underlying operating system.

字符串和嵌入的 null 字符Strings and embedded null characters

在.NET 中,String对象可以包含嵌入的 null 字符,作为字符串的长度的一部分进行计数。In .NET, a String object can include embedded null characters, which count as a part of the string's length. 但是,在某些语言如 C 和 c + + 中,null 字符指示字符串; 的末尾它不被视为字符串的一部分,并不计为字符串的长度的一部分。However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length. 这意味着 C 和 c + + 程序员提供的或用 C 或 c + + 编写的库可能会使有关字符串的以下常见假设不一定是有效时应用于String对象:This means that the following common assumptions that C and C++ programmers or libraries written in C or C++ might make about strings are not necessarily valid when applied to String objects:

  • 返回的值strlenwcslen函数不一定等于String.LengthThe value returned by the strlen or wcslen functions does not necessarily equal String.Length.

  • 由创建的字符串strcpy_swcscpy_s函数不是由创建的字符串一定要完全相同String.Copy方法。The string created by the strcpy_s or wcscpy_s functions is not necessarily identical to the string created by the String.Copy method.

您应该确保实例化该本机 C 和 c + + 代码String对象和代码传递String对象通过平台调用,请不要认为嵌入的 null 字符标记字符串的末尾。You should ensure that native C and C++ code that instantiates String objects, and code that is passed String objects through platform invoke, don't assume that an embedded null character marks the end of the string.

排序 (或比较) 一个字符串,以及搜索字符串时,还会区别处理字符串中嵌入的 null 字符。Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. 执行区分区域性的比较两个字符串,包括使用固定区域性的比较时,将忽略 null 字符。Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. 它们被视为仅为序号或不区分大小写的序号比较。They are considered only for ordinal or case-insensitive ordinal comparisons. 另一方面,嵌入的 null 字符始终被认为是使用方法,如搜索字符串时ContainsStartsWith,和IndexOfOn the other hand, embedded null characters are always considered when searching a string with methods such as Contains, StartsWith, and IndexOf.

字符串和已分区索引Strings and indexes

索引是的位置Char中的对象 (而不是 Unicode 字符) StringAn index is the position of a Char object (not a Unicode character) in a String. 索引是从零的字符串中的第一个位置开始的从零开始的、 非负数字。An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. 很多的搜索方法,如IndexOfLastIndexOf,返回其索引的一个字符或子字符串的字符串实例中。A number of search methods, such as IndexOf and LastIndexOf, return the index of a character or substring in the string instance.

Chars[Int32]属性,可以访问单个Char按其索引位置的字符串中的对象。The Chars[Int32] property lets you access individual Char objects by their index position in the string. 因为Chars[Int32]属性为默认属性 (在 Visual Basic 中) 或索引器 (在 C# 中),可以访问单个Char使用如下所示的代码的字符串中的对象。Because the Chars[Int32] property is the default property (in Visual Basic) or the indexer (in C#), you can access the individual Char objects in a string by using code such as the following. 此代码将查找空格或标点字符在字符串以确定该字符串包含的单词数。This code looks for white space or punctuation characters in a string to determine how many words the string contains.

using namespace System;

void main()
{
   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.
using System;

public class Example
{
   public static void Main()
   {
      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.
Module Example
   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)) 
            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构造,如以下示例所示。Because the String class implements the IEnumerable interface, you can also iterate through the Char objects in a string by using a foreach construct, as the following example shows.

using namespace System;

void main()
{
   String^ s1 = "This string consists of a single short sentence.";
   int nWords = 0;

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

public class Example
{
   public static void Main()
   {
      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.
Module Example
   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对象。Consecutive index values might not correspond to consecutive Unicode characters, because a Unicode character might be encoded as more than one Char object. 具体而言,一个字符串可能包含多字符的文本单位形成基字符后跟一个或多个组合字符或代理项对的。In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. 若要使用而不是 Unicode 字符Char对象,请使用System.Globalization.StringInfoTextElementEnumerator类。To work with Unicode characters instead of Char objects, use the System.Globalization.StringInfo and TextElementEnumerator classes. 下面的示例说明了处理的代码之间的差异Char对象和使用 Unicode 字符的代码。The following example illustrates the difference between code that works with Char objects and code that works with Unicode characters. 它将进行比较的字符数或每个单词的句子中的文本元素。It compares the number of characters or text elements in each word of a sentence. 该字符串包含两个基字符组合字符后跟的序列。The string includes two sequences of a base character followed by a combining character.

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Globalization;

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

   for each (Char ch in opening) {
      // Skip the ' character. 
      if (ch == '\x0027') continue;

      if (Char::IsWhiteSpace(ch) | (Char::IsPunctuation(ch))) {
         chars->Add(nChars);
         nChars = 0;
      }
      else {
         nChars++;
      }
   }

   TextElementEnumerator^ te = StringInfo::GetTextElementEnumerator(opening);
   while (te->MoveNext()) {
      String^ s = te->GetTextElement();   
      // Skip the ' character. 
      if (s == "\x0027") 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]); 
   Console::ReadLine();
}
// 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
using System;
using System.Collections.Generic;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // 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++;
         }
      }

      TextElementEnumerator te = 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
Imports System.Collections.Generic
Imports System.Globalization

Module Example
   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(&h0027) 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(&h0027) Then Continue Do
         If String.IsNullOrEmpty(s.Trim()) Or (s.Length = 1 AndAlso Char.IsPunctuation(Convert.ToChar(s))) 
            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类来枚举字符串中的所有文本元素。This example works with text elements by using the StringInfo.GetTextElementEnumerator method and the TextElementEnumerator class to enumerate all the text elements in a string. 您还可以检索通过调用包含每个文本元素的起始索引的数组StringInfo.ParseCombiningCharacters方法。You can also retrieve an array that contains the starting index of each text element by calling the StringInfo.ParseCombiningCharacters method.

详细了解使用的文本而不是单个单元Char值,请参阅StringInfo类。For more information about working with units of text rather than individual Char values, see the StringInfo class.

Null 字符串和空字符串Null strings and empty strings

已声明但尚未分配值的字符串是nullA string that has been declared but has not been assigned a value is null. 尝试在该字符串上调用方法将引发NullReferenceExceptionAttempting to call methods on that string throws a NullReferenceException. 空字符串是空字符串,这是一个字符串,其值从不同""或String.EmptyA null string is different from an empty string, which is a string whose value is "" or String.Empty. 在某些情况下,将 null 字符串或空字符串作为方法调用中的自变量传递引发异常。In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. 例如,传递一个 null 字符串到Int32.Parse方法会抛出ArgumentNullException,并传递空字符串,则会引发FormatExceptionFor example, passing a null string to the Int32.Parse method throws an ArgumentNullException, and passing an empty string throws a FormatException. 在其他情况下,方法自变量可以是空字符串或空字符串。In other cases, a method argument can be either a null string or an empty string. 例如,如果你要提供IFormattable类实现中的,你想要将 null 字符串和空字符串视为相等与常规 ("G") 格式说明符。For example, if you are providing an IFormattable implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier.

String类包括以下两个方便的方法,使您能够测试字符串是否为null或为空:The String class includes the following two convenience methods that enable you to test whether a string is null or empty:

  • IsNullOrEmpty指示字符串是否是任一null或等于String.EmptyIsNullOrEmpty, which indicates whether a string is either null or is equal to String.Empty. 此方法无需使用类似以下的代码:This method eliminates the need to use code such as the following:

    if (str == nullptr || str->Equals(String::Empty))
    
    if (str == null || str.Equals(String.Empty))
    
    If str Is Nothing OrElse str.Equals(String.Empty) Then
    
  • IsNullOrWhiteSpace指示字符串是否是null,等于String.Empty,或仅由空白字符组成。IsNullOrWhiteSpace, which indicates whether a string is null, equals String.Empty, or consists exclusively of white-space characters. 此方法无需使用类似以下的代码:This method eliminates the need to use code such as the following:

    if (str == nullptr || str->Equals(String::Empty) || str->Trim()->Equals(String::Empty))
    
    if (str == null || str.Equals(String.Empty) || str.Trim().Equals(String.Empty))
    
    If str Is Nothing OrElse str.Equals(String.Empty) OrElse str.Trim().Equals(String.Empty)
    

下面的示例使用IsNullOrEmpty中的方法IFormattable.ToString的自定义实现Temperature类。The following example uses the IsNullOrEmpty method in the IFormattable.ToString implementation of a custom Temperature class. 方法支持"G"、"C"、"F"和"K"格式字符串。The method supports the "G", "C", "F", and "K" format strings. 如果为空的格式字符串或格式字符串的值是null传递给方法,其值更改为"G"格式字符串。If an empty format string or a format string whose value is null is passed to the method, its value is changed to the "G" format string.

public:
   virtual String^ ToString(String^ format, IFormatProvider^ provider) 
   {
      if (String::IsNullOrEmpty(format)) format = "G";  
      if (provider == nullptr) provider = CultureInfo::CurrentCulture;
      
      switch (Convert::ToUInt16(format->ToUpperInvariant()))
      {
         // Return degrees in Celsius.    
         case 'G':
         case 'C':
            return temp.ToString("F2", provider) + L"�C";
         // Return degrees in Fahrenheit.
         case 'F': 
            return (temp * 9 / 5 + 32).ToString("F2", provider) + L"�F";
         // Return degrees in Kelvin.
         case 'K':   
            return (temp + 273.15).ToString();
         default:
            throw gcnew FormatException(
                  String::Format("The {0} format string is not supported.", 
                                 format));
      }                                   
   }
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));
   }                                   
}
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 类Immutability and the StringBuilder class

一个String对象称为不可变 (只读),因为它在创建后不能修改其值。A String object is called immutable (read-only), because its value cannot be modified after it has been created. 看起来要修改的方法String对象实际上返回一个新String包含修改的对象。Methods that appear to modify a String object actually return a new String object that contains the modification.

由于字符串是不可变的执行的字符串操作例程重复添加或删除操作到显示为单个字符串可以精确对显著的性能产生负面影响。Because strings are immutable, string manipulation routines that perform repeated additions or deletions to what appears to be a single string can exact a significant performance penalty. 例如,下面的代码使用的随机数生成器来创建具有范围从 0x0001 到 0x052F 中 1000 个字符的字符串。For example, the following code uses a random number generator to create a string with 1000 characters in the range 0x0001 to 0x052F. 尽管代码似乎使用字符串串联来将新字符附加到名为的现有字符串,但是str,它实际创建一个新String串联的每个操作的对象。Although the code appears to use string concatenation to append a new character to the existing string named str, it actually creates a new String object for each concatenation operation.

using namespace System;
using namespace System::IO;
using namespace System::Text;

void main()
{
   Random^ rnd = gcnew Random();

   String^ str = String::Empty;
   StreamWriter^ sw = gcnew StreamWriter(".\\StringFile.txt", 
                        false, Encoding::Unicode);

   for (int ctr = 0; ctr <= 1000; ctr++) {
      str += Convert::ToChar(rnd->Next(1, 0x0530)); 
      if (str->Length % 60 == 0)
         str += Environment::NewLine;          
   }                    
   sw->Write(str);
   sw->Close();
}
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 += Convert.ToChar(rnd.Next(1, 0x0530)); 
         if (str.Length % 60 == 0)
            str += Environment.NewLine;          
      }                    
      sw.Write(str);
      sw.Close();
   }
}
Imports System.IO
Imports System.Text

Module Example
   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, &h0530)) 
         If str.Length Mod 60 = 0 Then str += vbCrLf          
      Next                    
      sw.Write(str)
      sw.Close()
   End Sub
End Module

可以使用StringBuilder类而不是String类用于对字符串的值进行多个更改的操作。You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. 与不同的实例String类,StringBuilder对象是可变的; 当串联、 追加或删除从字符串的子字符串,在单个字符串执行的操作。Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. 当您已完成修改的值StringBuilder对象,可以调用其StringBuilder.ToString方法将其转换为字符串。When you have finished modifying the value of a StringBuilder object, you can call its StringBuilder.ToString method to convert it to a string. 下面的示例将替换String上一示例中用于连接为 0x0001 与 0x052F 到范围中的 1000 个随机字符StringBuilder对象。The following example replaces the String used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a StringBuilder object.

using namespace System;
using namespace System::IO;
using namespace System::Text;

void main()
{
   Random^ rnd = gcnew Random();

   StringBuilder^ sb = gcnew StringBuilder();
   StreamWriter^ sw = gcnew StreamWriter(".\\StringFile.txt", 
                        false, Encoding::Unicode);

   for (int ctr = 0; ctr <= 1000; ctr++) {
      sb->Append(Convert::ToChar(rnd->Next(1, 0x0530))); 
      if (sb->Length % 60 == 0)
         sb->AppendLine();          
   }                    
   sw->Write(sb->ToString());
   sw->Close();
}
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(Convert.ToChar(rnd.Next(1, 0x0530))); 
         if (sb.Length % 60 == 0)
            sb.AppendLine();          
      }                    
      sw.Write(sb.ToString());
      sw.Close();
   }
}
Imports System.IO
Imports System.Text

Module Example
   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, &h0530))) 
         If sb.Length Mod 60 = 0 Then sb.AppendLine()          
      Next                    
      sw.Write(sb.ToString())
      sw.Close()
   End Sub
End Module

区分区域性的操作与序号Ordinal vs. culture-sensitive operations

成员String类执行序号或区分区域性 (语言) 操作String对象。Members of the String class perform either ordinal or culture-sensitive (linguistic) operations on a String object. 序号操作将对每个数值Char对象。An ordinal operation acts on the numeric value of each Char object. 区分区域性的操作作用于的值String对象,并采用特定于区域性的大小写、 排序、 格式和考虑分析规则。A culture-sensitive operation acts on the value of the String object, and takes culture-specific casing, sorting, formatting, and parsing rules into account. 显式声明的区域性或隐式的当前区域性的上下文中执行区分区域性的操作。Culture-sensitive operations execute in the context of an explicitly declared culture or the implicit current culture. 它们执行相同的字符串时,两种类型的操作可以生成完全不同的结果。The two kinds of operations can produce very different results when they are performed on the same string.

.NET 还支持通过使用固定区域性的不区分区域性的语义字符串操作 (CultureInfo.InvariantCulture),这严格基于独立于区域的英语语言的区域性设置。.NET also supports culture-insensitive linguistic string operations by using the invariant culture (CultureInfo.InvariantCulture), which is loosely based on the culture settings of the English language independent of region. 与其他不同System.Globalization.CultureInfo保证设置,固定区域性的设置保持一致的单个计算机上,从系统到系统,以及跨版本的.NET。Unlike other System.Globalization.CultureInfo settings, the settings of the invariant culture are guaranteed to remain consistent on a single computer, from system to system, and across versions of .NET. 固定区域性可以跨所有区域性是视为一种类型的黑色框,以确保稳定性的字符串比较和排序。The invariant culture can be seen as a kind of black box that ensures stability of string comparisons and ordering across all cultures.

重要

如果你的应用程序如文件名的符号标识符做出安全决定或命名管道,或有关持久化数据,如 XML 文件中的基于文本的数据,该操作应使用序号比较,而不是区分区域性的比较。If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or about persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. 这是因为区分区域性的比较会有效时,生成不同结果根据区域性而序号比较仅取决于比较的字符的二进制值。This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters.

重要

执行字符串操作的大多数方法包括具有类型参数的重载StringComparison,这样您就可以指定是否该方法所执行的序号或区分区域性的操作。Most methods that perform string operations include an overload that has a parameter of type StringComparison, which enables you to specify whether the method performs an ordinal or culture-sensitive operation. 一般情况下,应调用此重载,以调用清除您的方法的意图。In general, you should call this overload to make the intent of your method call clear. 有关最佳实践和使用序号和区分区域性的字符串操作的指导,请参阅字符串使用最佳做法For best practices and guidance for using ordinal and culture-sensitive operations on strings, see Best Practices for Using Strings.

操作大小写分析和格式设置比较和排序,并为确定相等性测试可以是任一序号或区分区域性。Operations for casing, parsing and formatting, comparison and sorting, and testing for equality can be either ordinal or culture-sensitive. 以下各节讨论每个类别的操作。The following sections discuss each category of operation.

提示

应始终调用的方法重载,使调用清除您的方法的意图。You should always call a method overload that makes the intent of your method call clear. 例如,而不是调用Compare(String, String)要通过使用当前区域性的约定来执行区分区域性的比较两个字符串的方法应调用Compare(String, String, StringComparison)具有值的方法StringComparison.CurrentCulturecomparisonType自变量。For example, instead of calling the Compare(String, String) method to perform a culture-sensitive comparison of two strings by using the conventions of the current culture, you should call the Compare(String, String, StringComparison) method with a value of StringComparison.CurrentCulture for the comparisonType argument. 有关详细信息,请参阅有关使用字符串的最佳实践For more information, see Best Practices for Using Strings.

您可以下载排序权重表,包含在 Windows 操作系统、 排序和比较操作中使用的字符权重的信息的文本文件的一组和默认 Unicode排序规则元素表,适用于 Linux 和 macOS 的排序权重表。You can download the Sorting Weight Tables, a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, and the Default Unicode Collation Element Table, the sort weight table for Linux and macOS.

大小写Casing

大小写规则确定如何更改大小写的 Unicode 字符;例如,从小写到大写。Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. 通常情况下,字符串比较之前执行的大小写操作。Often, a casing operation is performed before a string comparison. 例如,一个字符串,可能会转换为大写,以便它可以与另一个大写的字符串进行比较。For example, a string might be converted to uppercase so that it can be compared with another uppercase string. 可以将转换为小写通过调用一个字符串中的字符ToLowerToLowerInvariant方法,并且你可以将它们转换为大写通过调用ToUpperToUpperInvariant方法。You can convert the characters in a string to lowercase by calling the ToLower or ToLowerInvariant method, and you can convert them to uppercase by calling the ToUpper or ToUpperInvariant method. 此外,还可以使用TextInfo.ToTitleCase方法将字符串转换为词首字母大写。In addition, you can use the TextInfo.ToTitleCase method to convert a string to title case.

大小写的操作可以根据当前区域性、 指定的区域性或固定区域性的规则。Casing operations can be based on the rules of the current culture, a specified culture, or the invariant culture. 因为大小写映射可能会变化,具体取决于所用的区域性,大小写操作的结果可以因区域性。Because case mappings can vary depending on the culture used, the result of casing operations can vary based on culture. 在大小写的实际差异有三种:The actual differences in casing are of three kinds:

  • 中的拉丁语 I 的大写首字母大小写映射的差异 (U + 0049),拉丁文小写字母 I (U + 0069),LATIN CAPITAL LETTER I (U + 0130),上面的点和拉丁文小写字母无点 I (U + 0131)。Differences in the case mapping of LATIN CAPITAL LETTER I (U+0049), LATIN SMALL LETTER I (U+0069), LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130), and LATIN SMALL LETTER DOTLESS I (U+0131). TR-TR (土耳其语 (土耳其)) 和 (阿塞拜疆,拉丁语) az-Latn-AZ 文化中,在和中的 tr、 az 和 az Latn 非特定区域性,LATIN CAPITAL LETTER I 的小写等效项是拉丁文小写字母无点 I、 和的拉丁文小写字母 I 的大写等效项是上面带点的拉丁文大写字母 I。In the tr-TR (Turkish (Turkey)) and az-Latn-AZ (Azerbaijan, Latin) cultures, and in the tr, az, and az-Latn neutral cultures, the lowercase equivalent of LATIN CAPITAL LETTER I is LATIN SMALL LETTER DOTLESS I, and the uppercase equivalent of LATIN SMALL LETTER I is LATIN CAPITAL LETTER I WITH DOT ABOVE. 在所有其他文化中,其中包括固定区域性,拉丁文小写字母 I 和 LATIN CAPITAL LETTER 我是小写和大写等效项。In all other cultures, including the invariant culture, LATIN SMALL LETTER I and LATIN CAPITAL LETTER I are lowercase and uppercase equivalents.

    下面的示例演示如何设计的字符串比较,以防止文件系统访问权限可能会失败是否它依赖于区分区域性的大小写比较。The following example demonstrates how a string comparison designed to prevent file system access can fail if it relies on a culture-sensitive casing comparison. (固定区域性的大小写约定应该已使用。)(The casing conventions of the invariant culture should have been used.)

    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
    
    Imports System.Globalization
    Imports System.Threading
    
    Module Example
       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
    
  • 大小写映射中固定区域性和所有其他区域性之间的差异。Differences in case mappings between the invariant culture and all other cultures. 在这些情况下,使用固定区域性的大小写规则更改为大写或小写字符返回的相同字符。In these cases, using the casing rules of the invariant culture to change a character to uppercase or lowercase returns the same character. 对于所有其他区域性,它将返回不同的字符。For all other cultures, it returns a different character. 下表列出了一些受影响的字符。Some of the affected characters are listed in the following table.

    字符Character 如果更改为If changed to 返回Returns
    微米登录 (U + 00B5)MICRON SIGN (U+00B5) 大写Uppercase 希腊文大写字母 MU (U +-39 C)GREEK CAPITAL LETTER MU (U+-39C)
    拉丁文大写字母 I 带点上方 (U + 0130)LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130) 小写Lowercase 拉丁文小写字母 I (U + 0069)LATIN SMALL LETTER I (U+0069)
    拉丁文小写字母无点我 (U + 0131)LATIN SMALL LETTER DOTLESS I (U+0131) 大写Uppercase 拉丁文大写字母 I (U + 0049)LATIN CAPITAL LETTER I (U+0049)
    拉丁文小写字母长 S (U + 017F)LATIN SMALL LETTER LONG S (U+017F) 大写Uppercase 拉丁文大写字母 S (U + 0053)LATIN CAPITAL LETTER S (U+0053)
    小写字母 Z 带抑扬符拉丁文大写字母 D (U + 01C 5)LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON (U+01C5) 小写Lowercase 拉丁文小写字母 DZ 带抑扬符 (U + 01C 6)LATIN SMALL LETTER DZ WITH CARON (U+01C6)
    组合希腊语 YPOGEGRAMMENI (U + 0345)COMBINING GREEK YPOGEGRAMMENI (U+0345) 大写Uppercase 希腊文大写字母 IOTA (U + 0399)GREEK CAPITAL LETTER IOTA (U+0399)
  • ASCII 字符范围中的两个字母大小写混合的对的大小写映射之间的差异。Differences in case mappings of two-letter mixed-case pairs in the ASCII character range. 在大多数文化中,两个字母大小写混合的对等于等效的双字母大写或小写字母对。In most cultures, a two-letter mixed-case pair is equal to the equivalent two-letter uppercase or lowercase pair. 这是不为以下区域中的以下两个字母对,则返回 true,因为每种情况下它们不同于二合字母:This is not true for the following two-letter pairs in the following cultures, because in each case they are compared to a digraph:

    • "lJ"和"nJ"HR-HR (克罗地亚语 (克罗地亚)) 区域性中。"lJ" and "nJ" in the hr-HR (Croatian (Croatia)) culture.

    • "cH"cs CZ (捷克语 (捷克共和国)) 和 sk-SK (斯洛伐克语 (斯洛伐克)) 文化中。"cH" in the cs-CZ (Czech (Czech Republic)) and sk-SK (Slovak (Slovakia)) cultures.

    • "aA"DA-DK (丹麦语 (丹麦)) 区域性中。"aA" in the da-DK (Danish (Denmark)) culture.

    • "cS"、"dZ"、"dZS"、"nY"、"sZ"、"tY"和"zS"HU-HU (匈牙利语 (匈牙利)) 区域性中。"cS", "dZ", "dZS", "nY", "sZ", "tY", and "zS" in the hu-HU (Hungarian (Hungary)) culture.

    • "cH"和"lL"es ES_tradnl (西班牙语 (西班牙,传统风格)) 区域性中。"cH" and "lL" in the es-ES_tradnl (Spanish (Spain, Traditional Sort)) culture.

    • "cH"、"gI"、"kH"、"nG""nH"、"pH","qU,"tH"和"tR"vi VN (越南语 (越南)) 区域性中的。"cH", "gI", "kH", "nG" "nH", "pH", "qU', "tH", and "tR" in the vi-VN (Vietnamese (Vietnam)) culture.

    但是,很少会遇到的情况下,这些对区分区域性的比较在其中创建问题,因为这些对很少出现在固定的字符串或标识符。However, it is unusual to encounter a situation in which a culture-sensitive comparison of these pairs creates problems, because these pairs are uncommon in fixed strings or identifiers.

下面的示例说明了一些在大小写规则区域性将字符串转换为大写时之间的差异。The following example illustrates some of the differences in casing rules between cultures when converting strings to uppercase.

using namespace System;
using namespace System::Globalization;
using namespace System::IO;

String^ ShowHexValue(String^ s);

void main()
{
   StreamWriter^ sw = gcnew StreamWriter(".\\case.txt");   
   array<String^>^ words = gcnew array<String^> { L"file", L"sıfır", L"Dženana" };
   array<CultureInfo^>^ cultures = gcnew array<CultureInfo^> { CultureInfo::InvariantCulture, 
                                                               gcnew CultureInfo("en-US"),  
                                                               gcnew CultureInfo("tr-TR") };

   for each (String^ word in words) {
      sw->WriteLine("{0}:", word);
      for each (CultureInfo^ 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();
}

String^ ShowHexValue(String^ s)
{
   String^ retval = nullptr;
   for each (Char ch in s) {
      array<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 
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 
Imports System.Globalization
Imports System.IO

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

分析和格式设置Parsing and formatting

格式设置和分析为反向操作。Formatting and parsing are inverse operations. 格式设置规则确定如何将一个值,如日期和时间或数字转换为其字符串表示形式,而分析规则确定如何将字符串表示形式转换为一个值,例如日期和时间。Formatting rules determine how to convert a value, such as a date and time or a number, to its string representation, whereas parsing rules determine how to convert a string representation to a value such as a date and time. 格式化和分析规则都依赖于区域性的约定。Both formatting and parsing rules are dependent on cultural conventions. 下面的示例演示解释特定于区域性的日期字符串时,可能会出现多义性。The following example illustrates the ambiguity that can arise when interpreting a culture-specific date string. 如果不知道用于生成的日期字符串的区域性的约定,不可能知道 2011-03-01、 2011 年 3 月 1 日和 2011-03/01-表示 2011 年 1 月 3 日或 2011 年 3 月 1 日。Without knowing the conventions of the culture that was used to produce a date string, it is not possible to know whether 03/01/2011, 3/1/2011, and 01/03/2011 represent January 3, 2011 or March 1, 2011.

using namespace System;
using namespace System::Globalization;

void main()
{
   DateTime^ date = gcnew DateTime(2011, 3, 1);
   array<CultureInfo^>^ cultures = gcnew array<CultureInfo^> { CultureInfo::InvariantCulture, 
                                                               gcnew CultureInfo("en-US"), 
                                                               gcnew CultureInfo("fr-FR") };

   for each (CultureInfo^ 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
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
Imports System.Globalization

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

同样,如下面的示例所示,单个字符串可以生成不同的日期,具体取决于在分析操作中使用的约定的区域性。Similarly, as the following example shows, a single string can produce different dates depending on the culture whose conventions are used in the parsing operation.

using namespace System;
using namespace System::Globalization;

void main()
{
   String^ dateString = "07/10/2011";
   array<CultureInfo^>^ cultures = gcnew array<CultureInfo^> { 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");
   for each (CultureInfo^ 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

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
Imports System.Globalization

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

字符串比较和排序String comparison and sorting

用于比较和排序字符串的约定因因区域性而异。Conventions for comparing and sorting strings vary from culture to culture. 例如,排序顺序可能基于拼音或基于字符的可视表示形式。For example, the sort order may be based on phonetics or on the visual representation of characters. 在东亚语言中,按文字的笔画和部首对字符进行排序。In East Asian languages, characters are sorted by the stroke and radical of ideographs. 排序也取决于字母表使用的排序语言和区域性。Sorting also depends on the order languages and cultures use for the alphabet. 例如,丹麦语中有“Æ”字符,它在字母表中排在“Z”之后。For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. 此外,比较可以区分大小写或不区分大小写,并且在某些情况下的大小写规则也因区域性而异。In addition, comparisons can be case-sensitive or case-insensitive, and in some cases casing rules also differ by culture. 序号比较,但是,使用时比较和排序字符串的字符串中的单个字符的 Unicode 码位。Ordinal comparison, on the other hand, uses the Unicode code points of individual characters in a string when comparing and sorting strings.

排序规则用于确定与每个其他 Unicode 字符的字母顺序和如何两个字符串进行比较。Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. 例如,String.Compare(String, String, StringComparison)方法比较两个字符串基于StringComparison参数。For example, the String.Compare(String, String, StringComparison) method compares two strings based on the StringComparison parameter. 如果参数值StringComparison.CurrentCulture,该方法执行使用当前区域性的约定的语义比较,如果参数值StringComparison.Ordinal,该方法执行序号比较。If the parameter value is StringComparison.CurrentCulture, the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is StringComparison.Ordinal, the method performs an ordinal comparison. 因此,如以下示例所示,如果当前区域性为美国英语,在首次调用String.Compare(String, String, StringComparison)方法 (使用区分区域性的比较) 将视为"a"小于"A",但第二个调用同一方法 (使用序号比较) 将视为"a"大于"A"。Consequently, as the following example shows, if the current culture is U.S. English, the first call to the String.Compare(String, String, StringComparison) method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A".

using namespace System;
using namespace System::Globalization;
using namespace System::Threading;

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
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
Imports System.Globalization
Imports System.Threading

Module Example
   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 支持 word、 字符串和序号排序规则:.NET supports word, string, and ordinal sort rules:

  • 单词排序在其中某些非字母数字 Unicode 字符可能会有特殊的权重分配给他们执行区分区域性的比较的字符串。A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. 例如,连字符 (-) 可能很小的权重分配给它,以便"coop"和"co-op"显示彼此排序列表中。For example, the hyphen (-) might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. 有关一系列String方法比较两个字符串使用单词排序规则,请参阅按类别的字符串操作部分。For a list of the String methods that compare two strings using word sort rules, see the String operations by category section.

  • 字符串排序还执行区分区域性的比较。A string sort also performs a culture-sensitive comparison. 它相当于单词排序,只不过有任何特殊的情况下,并且所有的非字母数字符号放在所有字母数字 Unicode 字符之前。It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. 可以通过调用通过使用字符串排序规则比较两个字符串CompareInfo.Compare具有的方法重载options为参数提供的值为CompareOptions.StringSortTwo strings can be compared using string sort rules by calling the CompareInfo.Compare method overloads that have an options parameter that is supplied a value of CompareOptions.StringSort. 请注意,这是.NET 提供的用于比较两个字符串使用字符串排序规则的唯一方法。Note that this is the only method that .NET provides to compare two strings using string sort rules.

  • 序号排序对基于每个数值的字符串进行比较Char字符串中的对象。An ordinal sort compares strings based on the numeric value of each Char object in the string. 序号比较是自动区分大小写,因为一个字符的大写和小写版本具有不同的码位。An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. 但是,如果用例并不重要,可以指定不区分大小写的序号比较。However, if case is not important, you can specify an ordinal comparison that ignores case. 这相当于将字符串转换为大写的通过使用固定区域性,然后对结果执行序号比较。This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. 有关一系列String方法比较两个字符串使用序号排序规则,请参阅按类别的字符串操作部分。For a list of the String methods that compare two strings using ordinal sort rules, see the String operations by category section.

区分区域性的比较是显式或隐式使用任何比较CultureInfo对象,包括由指定的固定区域性CultureInfo.InvariantCulture属性。A culture-sensitive comparison is any comparison that explicitly or implicitly uses a CultureInfo object, including the invariant culture that is specified by the CultureInfo.InvariantCulture property. 隐式区域性是由指定的当前区域性Thread.CurrentCultureCultureInfo.CurrentCulture属性。The implicit culture is the current culture, which is specified by the Thread.CurrentCulture and CultureInfo.CurrentCulture properties. 没有相当大的字母字符在排序顺序中的变体 (即,其字符Char.IsLetter属性返回true) 跨区域性。There is considerable variation in the sort order of alphabetic characters (that is, characters for which the Char.IsLetter property returns true) across cultures. 可以指定通过提供使用特定区域性的约定的区分区域性的比较CultureInfo对象传递给字符串比较方法,如Compare(String, String, CultureInfo, CompareOptions)You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a CultureInfo object to a string comparison method such as Compare(String, String, CultureInfo, CompareOptions). 可以指定使用当前区域性的约定,通过提供区分区域性的比较StringComparison.CurrentCultureStringComparison.CurrentCultureIgnoreCase,或任何成员CompareOptions以外的其他枚举CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase到相应重载的Compare方法。You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, or any member of the CompareOptions enumeration other than CompareOptions.Ordinal or CompareOptions.OrdinalIgnoreCase to an appropriate overload of the Compare method. 一般适合用于排序而不是序号比较是区分区域性的比较。A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. 序号比较是一般适合用于确定两个字符串是否相等 (即,用于确定标识) 而不是区分区域性的比较。An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not.

下面的示例说明了区域性敏感型和序号比较之间的差异。The following example illustrates the difference between culture-sensitive and ordinal comparison. 该示例计算结果的三个字符串、"Apple"、"Æble"和"AEble",以使用序号比较和 DA-DK 并 EN-US 区域性的约定 (其中每个为时的默认区域性Compare调用方法)。The example evaluates three strings, "Apple", "Æble", and "AEble", using ordinal comparison and the conventions of the da-DK and en-US cultures (each of which is the default culture at the time the Compare method is called). 因为丹麦语语言字符"存储"视为单个字母,并对其进行排序后"Z"字母表中,字符串"Æble"大于"Apple"。Because the Danish language treats the character "Æ" as an individual letter and sorts it after "Z" in the alphabet, the string "Æble" is greater than "Apple". 但是,"Æble"是不被视为等效于"AEble",因此"Æble"也是晚于"AEble"。However, "Æble" is not considered equivalent to "AEble", so "Æble" is also greater than "AEble". EN-US 区域性不包括字母"存储",但将其视为等效于"AE",解释了为什么"Æble"小于"Apple"但等于"AEble"。The en-US culture doesn't include the letter"Æ" but treats it as equivalent to "AE", which explains why "Æble" is less than "Apple" but equal to "AEble". 序号比较,但是,将视为"Apple"小于"Æble"和"Æble"必须晚于"AEble"。Ordinal comparison, on the other hand, considers "Apple" to be less than "Æble", and "Æble" to be greater than "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
Imports System.Globalization
Imports System.Threading

Public Module Example
   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

使用以下常规准则来选择适当的排序或字符串比较方法:Use the following general guidelines to choose an appropriate sorting or string comparison method:

  • 如果您希望根据用户的区域性的字符串进行排序,您应该对它们基于当前区域性的约定进行排序。If you want the strings to be ordered based on the user's culture, you should order them based on the conventions of the current culture. 如果用户的区域性发生更改,也将相应地更改排序字符串的顺序。If the user's culture changes, the order of sorted strings will also change accordingly. 例如,同义词库应用程序应始终进行排序基于用户的区域性的单词。For example, a thesaurus application should always sort words based on the user's culture.

  • 如果你想要进行排序的字符串根据特定区域性的约定,则应通过提供订购它们CultureInfo对象,表示该区域性的比较方法。If you want the strings to be ordered based on the conventions of a specific culture, you should order them by supplying a CultureInfo object that represents that culture to a comparison method. 例如,教授学生特定语言设计的应用程序,在你希望字符串进行排序根据使用该语言的区域性之一的约定。For example, in an application designed to teach students a particular language, you want strings to be ordered based on the conventions of one of the cultures that speaks that language.

  • 如果您希望字符串的顺序,以跨区域性将保持不变,应基于固定区域性的约定也可以使用序号比较。If you want the order of strings to remain unchanged across cultures, you should order them based on the conventions of the invariant culture or use an ordinal comparison. 例如,您将使用序号排序来组织的文件、 进程、 互斥体的名称或命名管道。For example, you would use an ordinal sort to organize the names of files, processes, mutexes, or named pipes.

  • 有关涉及安全决策 (例如用户名是否有效) 的比较,您始终应执行序号为确定相等性测试通过调用的重载Equals方法。For a comparison that involves a security decision (such as whether a username is valid), you should always perform an ordinal test for equality by calling an overload of the Equals method.

备注

区分区域性的排序和大小写的字符串比较中使用的规则取决于版本的.NET。The culture-sensitive sorting and casing rules used in string comparison depend on the version of the .NET. 在.NET Framework 4.5 和更高版本上运行Windows 8Windows 8操作系统系统、 排序、 大小写、 规范化和 Unicode 字符信息是否符合 Unicode 6.0 标准。In the .NET Framework 4.5 and later versions running on the Windows 8Windows 8 operating system, sorting, casing, normalization, and Unicode character information conforms to the Unicode 6.0 standard. 在其他 Windows 操作系统的系统,它符合 Unicode 5.0 标准。On other Windows operating systems, it conforms to the Unicode 5.0 standard. 在.NET Core,这取决于基础操作系统支持的 Unicode 标准版本。On .NET Core, it depends on the version of the Unicode Standard supported by the underlying operating system.

有关 word、 字符串和序号排序规则的详细信息,请参阅System.Globalization.CompareOptions主题。For more information about word, string, and ordinal sort rules, see the System.Globalization.CompareOptions topic. 有关何时使用每个规则的其他建议,请参阅字符串使用最佳做法For additional recommendations on when to use each rule, see Best Practices for Using Strings.

通常,不要调用比较方法,如字符串Compare直接以确定字符串的排序顺序。Ordinarily, you don't call string comparison methods such as Compare directly to determine the sort order of strings. 相反,如排序方法通过调用比较方法Array.SortList<T>.SortInstead, comparison methods are called by sorting methods such as Array.Sort or List<T>.Sort. 下面的示例执行四个不同的排序操作 (使用当前区域性,使用固定区域性的单词排序、 序号排序和使用固定区域性的字符串排序单词排序),无需显式调用的字符串比较方法,尽管它们指定要使用的比较类型。The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method, although they do specify the type of comparison to use. 请注意,每种类型的排序将生成其数组中的字符串的唯一排序。Note that each type of sort produces a unique ordering of strings in its array.

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Globalization;

// IComparer<String> implementation to perform string sort. 
ref class SCompare : System::Collections::Generic::IComparer<String^>
{
public:
   SCompare() {};

   virtual int Compare(String^ x, String^ y)
   {
      return CultureInfo::CurrentCulture->CompareInfo->Compare(x, y, CompareOptions::StringSort);
   }
};

void main()
{
   array<String^>^ strings = gcnew array<String^> { "coop", "co-op", "cooperative", 
                                                    L"co\x00ADoperative", L"c�ur", "coeur" };

   // Perform a word sort using the current (en-US) culture. 
   array<String^>^ current = gcnew array<String^>(strings->Length); 
   strings->CopyTo(current, 0); 
   Array::Sort(current, StringComparer::CurrentCulture);

   // Perform a word sort using the invariant culture. 
   array<String^>^ invariant = gcnew array<String^>(strings->Length);
   strings->CopyTo(invariant, 0); 
   Array::Sort(invariant, StringComparer::InvariantCulture);

   // Perform an ordinal sort. 
   array<String^>^ ordinal = gcnew array<String^>(strings->Length);
   strings->CopyTo(ordinal, 0); 
   Array::Sort(ordinal, StringComparer::Ordinal);

   // Perform a string sort using the current culture. 
   array<String^>^ stringSort = gcnew array<String^>(strings->Length);
   strings->CopyTo(stringSort, 0); 
   Array::Sort(stringSort, gcnew 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] );          
}
// 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
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
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim strings() As String = { "coop", "co-op", "cooperative", 
                                  "co" + ChrW(&h00AD) + "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

提示

在内部,.NET 使用排序关键字支持区分区域性的字符串比较。Internally, .NET uses sort keys to support culturally sensitive string comparison. 对于字符串中的每个字符,都赋予若干类排序权重,包括字母、大小写和变音符。Each character in a string is given several categories of sort weights, including alphabetic, case, and diacritic. 排序键,由表示SortKey类中,为特定字符串提供这些权重的库。A sort key, represented by the SortKey class, provides a repository of these weights for a particular string. 如果您的应用程序执行大量的搜索或排序对一组相同的字符串的操作,可以通过生成并存储它使用的所有字符串的排序键来提高其性能。If your app performs a large number of searching or sorting operations on the same set of strings, you can improve its performance by generating and storing sort keys for all the strings that it uses. 当需要进行排序或比较操作时,您将使用排序键,而不是字符串。When a sort or comparison operation is required, you use the sort keys instead of the strings. 有关更多信息,请参见 SortKey 类。For more information, see the SortKey class.

如果未指定的字符串比较约定,如排序方法Array.Sort(Array)对字符串执行区分区域性的、 区分大小写的排序。If you don't specify a string comparison convention, sorting methods such as Array.Sort(Array) perform a culture-sensitive, case-sensitive sort on strings. 下面的示例演示如何更改当前区域性会影响排序字符串数组中的顺序。The following example illustrates how changing the current culture affects the order of sorted strings in an array. 它创建三个字符串的数组。It creates an array of three strings. 首先,它将 System.Threading.Thread.CurrentThread.CurrentCulture 属性设置为 en-US,并调用 Array.Sort(Array) 方法。First, it sets the System.Threading.Thread.CurrentThread.CurrentCulture property to en-US and calls the Array.Sort(Array) method. 结果的排序顺序基于排序为英语 (美国) 区域性的约定。The resulting sort order is based on sorting conventions for the English (United States) culture. 接着,此示例将 System.Threading.Thread.CurrentThread.CurrentCulture 属性设置为 da-DK 并再次调用 Array.Sort 方法。Next, the example sets the System.Threading.Thread.CurrentThread.CurrentCulture property to da-DK and calls the Array.Sort method again. 请注意,最终排序顺序与使用 en-US 时的结果不一样,因为这次使用的是针对丹麦语(丹麦)的排序约定。Notice how the resulting sort order differs from the en-US results because it uses the sorting conventions for Danish (Denmark).

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

警告

如果你在比较字符串的主要用途是确定它们是否相等,则应调用String.Equals方法。If your primary purpose in comparing strings is to determine whether they are equal, you should call the String.Equals method. 通常情况下,应使用Equals要执行序号比较。Typically, you should use Equals to perform an ordinal comparison. String.Compare方法主要用于对字符串进行排序。The String.Compare method is intended primarily to sort strings.

字符串搜索方法,如String.StartsWithString.IndexOf,还可以执行区分区域性的或序号字符串比较。String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons. 下面的示例演示使用序号和区分区域性的比较之间的差异IndexOf方法。The following example illustrates the differences between ordinal and culture-sensitive comparisons using the IndexOf method. 在其中的当前区域性为英语 (美国) 的区分区域性的搜索将视为"oe"以匹配连字"œ"的子字符串。A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". 因为软连字符 (U + 00AD) 是零宽字符,则搜索将软连字符视为等效于Empty和字符串的开头处找到的匹配项。Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to Empty and finds a match at the beginning of the string. 序号搜索,但是,找不到匹配项在任一情况下。An ordinal search, on the other hand, does not find a match in either case.

using namespace System;

void FindInString(String^ s, String^ substring, StringComparison options);

void main()
{
   // Search for "oe" and "�u" in "�ufs" and "oeufs".
   String^ s1 = L"�ufs";
   String^ s2 = L"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 = L"co\x00ADoperative";
   FindInString(s3, L"\x00AD", StringComparison::CurrentCulture);
   FindInString(s3, L"\x00AD", StringComparison::Ordinal);
}

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 oufs at position 0
//      'oe' not found in oufs
//      'ou' found in oeufs at position 0
//      'ou' not found in oeufs
//
//      '-' found in co-operative at position 0
//      '-' found in co-operative at position 2
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
Module Example
   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(&h00AD)
      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
         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

搜索字符串Searching Strings

字符串搜索方法,如String.StartsWithString.IndexOf,还可以执行区分区域性的或在指定的字符串中找到的序号字符串比较,以确定是否有字符或子字符串。String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons to determine whether a character or substring is found in a specified string.

中的搜索方法String类的单个字符,如搜索IndexOf方法或一组字符,如IndexOfAny方法中,所有执行序号搜索。The search methods in the String class that search for an individual character, such as the IndexOf method, or one of a set of characters, such as the IndexOfAny method, all perform an ordinal search. 若要执行区分区域性的搜索的字符,必须调用CompareInfo等方法CompareInfo.IndexOf(String, Char)CompareInfo.LastIndexOf(String, Char)To perform a culture-sensitive search for a character, you must call a CompareInfo method such as CompareInfo.IndexOf(String, Char) or CompareInfo.LastIndexOf(String, Char). 请注意,可以非常不同的搜索的字符使用序号和区分区域性的比较结果。Note that the results of searching for a character using ordinal and culture-sensitive comparison can be very different. 例如,如连字"存储"的预构成 Unicode 字符 (U + 00 C 6) 的搜索可能匹配正确的顺序,如 AE 及其组件的任何匹配项 (U + 041U + 0045),根据区域性。For example, a search for a precomposed Unicode character such as the ligature "Æ" (U+00C6) might match any occurrence of its components in the correct sequence, such as "AE" (U+041U+0045), depending on the culture. 下面的示例说明了之间的差异String.IndexOf(Char)CompareInfo.IndexOf(String, Char)方法搜索的单个字符时。The following example illustrates the difference between the String.IndexOf(Char) and CompareInfo.IndexOf(String, Char) methods when searching for an individual character. 连字"存储"(U + 00E6) 是在字符串中找到"空中"时使用 EN-US 区域性的约定,但不是使用 DA-DK 区域性的约定时或执行序号比较时。The ligature "æ" (U+00E6) is found in the string "aerial" when using the conventions of the en-US culture, but not when using the conventions of the da-DK culture or when performing an ordinal comparison.

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
Imports System.Globalization

Module Example
   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类搜索字符串,而不是一个字符执行区分区域性的搜索,如果搜索选项未显式指定的类型参数的方法StringComparisonOn the other hand, String class methods that search for a string rather than a character perform a culture-sensitive search if search options are not explicitly specified by a parameter of type StringComparison. 唯一的例外是Contains,该文件将执行序号搜索。The sole exception is Contains, which performs an ordinal search.

为确定相等性测试Testing for equality

使用String.Compare方法来确定两个字符串在排序顺序中的关系。Use the String.Compare method to determine the relationship of two strings in the sort order. 通常情况下,这是区分区域性的操作。Typically, this is a culture-sensitive operation. 与此相反,调用String.Equals方法来测试相等性。In contrast, call the String.Equals method to test for equality. 为确定相等性测试通常比较用户输入与某个已知的字符串,例如有效的用户名、 密码或文件系统路径,因为它通常是一个序号操作。Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation.

警告

可以通过调用测试相等性String.Compare方法,并确定返回值是否为零。It is possible to test for equality by calling the String.Compare method and determining whether the return value is zero. 但是,不建议这样做。However, this practice is not recommended. 若要确定两个字符串,应调用的重载之一String.Equals方法。To determine whether two strings are equal, you should call one of the overloads of the String.Equals method. 若要调用的首选的重载为实例Equals(String, StringComparison)方法或静态Equals(String, String, StringComparison)方法,因为这两种方法包括System.StringComparison显式指定的比较类型的参数。The preferred overload to call is either the instance Equals(String, StringComparison) method or the static Equals(String, String, StringComparison) method, because both methods include a System.StringComparison parameter that explicitly specifies the type of comparison.

下面的示例说明了执行区分区域性的比较相等时应改为使用一个序号。The following example illustrates the danger of performing a culture-sensitive comparison for equality when an ordinal one should be used instead. 在这种情况下,代码的目的是通过执行不区分大小写比较的字符串"FILE://"与 URL 开头"FILE://"或"file://"开头的 Url 从禁止文件系统访问权限。In this case, the intent of the code is to prohibit file system access from URLs that begin with "FILE://" or "file://" by performing a case-insensitive comparison of the beginning of a URL with the string "FILE://". 但是,如果以"file://"开头的 URL 上使用土耳其语 (土耳其) 区域性执行区分区域性的比较,则为确定相等性比较失败,因为小写"i"的土耳其语的大写等效项为"i"而不是"I"。However, if a culture-sensitive comparison is performed using the Turkish (Turkey) culture on a URL that begins with "file://", the comparison for equality fails, because the Turkish uppercase equivalent of the lowercase "i" is "İ" instead of "I". 因此,无意中允许的文件系统访问。As a result, file system access is inadvertently permitted. 但是,如果执行序号比较,则为确定相等性比较成功,并拒绝文件系统访问。On the other hand, if an ordinal comparison is performed, the comparison for equality succeeds, and file system access is denied.

using namespace System;
using namespace System::Globalization;
using namespace System::Threading;

bool TestForEquality(String^ str, StringComparison cmp);

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);
}

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.
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.
Imports System.Globalization
Imports System.Threading

Module Example
   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.

标准化Normalization

某些 Unicode 字符具有多种表示形式。Some Unicode characters have multiple representations. 例如,下面的代码点的任何可表示字母"ắ":For example, any of the following code points can represent the letter "ắ":

  • U + 1EAFU+1EAF

  • U+0103 U+0301U+0103 U+0301

  • U+0061 U+0306 U+0301U+0061 U+0306 U+0301

单个字符的多种表示形式使搜索、 排序、 匹配和其他字符串操作变得复杂。Multiple representations for a single character complicate searching, sorting, matching, and other string operations.

Unicode 标准定义了名为返回一个 Unicode 字符的任何其等效的二进制表示形式的二进制表示形式的规范化的过程。The Unicode standard defines a process called normalization that returns one binary representation of a Unicode character for any of its equivalent binary representations. 规范化可以使用多种算法,调用下列不同的规则的规范化形式。Normalization can use several algorithms, called normalization forms, that follow different rules. .NET 支持 Unicode 范式 C、 D、 KC 和 KD。.NET supports Unicode normalization forms C, D, KC, and KD. 当字符串被正常化为相同的范式时,它们可以通过使用序号比较进行比较。When strings have been normalized to the same normalization form, they can be compared by using ordinal comparison.

序号比较是对应的 Unicode 标量值的二进制比较Char中每个字符串的对象。An ordinal comparison is a binary comparison of the Unicode scalar value of corresponding Char objects in each string. String类包括许多方法可以执行序号比较,其中包括:The String class includes a number of methods that can perform an ordinal comparison, including the following:

您可以确定一个字符串,指示是否被规范化为范式 C 通过调用String.IsNormalized()方法,或者可以调用String.IsNormalized(NormalizationForm)方法,以确定是否将字符串规范化为指定的范式。You can determine whether a string is normalized to normalization form C by calling the String.IsNormalized() method, or you can call the String.IsNormalized(NormalizationForm) method to determine whether a string is normalized to a specified normalization form. 您还可以调用String.Normalize()方法将字符串转换到范式 C,也可以调用String.Normalize(NormalizationForm)方法将字符串转换为指定的范式。You can also call the String.Normalize() method to convert a string to normalization form C, or you can call the String.Normalize(NormalizationForm) method to convert a string to a specified normalization form. 有关规范化和比较字符串的分步信息,请参阅Normalize()Normalize(NormalizationForm)方法。For step-by-step information about normalizing and comparing strings, see the Normalize() and Normalize(NormalizationForm) methods.

下面的简单示例说明了字符串标准化。The following simple example illustrates string normalization. 它在三个不同字符串中的三种不同方式定义了字母"ố",并使用序号比较相等来确定每个字符串不同于其他两个字符串。It defines the letter "ố" in three different ways in three different strings, and uses an ordinal comparison for equality to determine that each string differs from the other two strings. 它然后将每个字符串转换为受支持的规范化窗体,并再次执行序号比较每个字符串中指定的范式。It then converts each string to the supported normalization forms, and again performs an ordinal comparison of each string in a specified normalization form. 在每种情况下,第二个相等性测试显示字符串相等。In each case, the second test for equality shows that the strings are equal.

using namespace System;
using namespace System::Globalization;
using namespace System::IO;
using namespace System::Text;

public ref class Example
{
private:
   StreamWriter^ sw;

   void TestForEquality(... array<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));
   }

   String^ ShowBytes(String^ str)
   {
      String^ result = nullptr;
      for each (Char ch in str)
         result += String::Format("{0} ", Convert::ToUInt16(ch).ToString("X4")); 
      return result->Trim();            
   } 

   array<String^>^ NormalizeStrings(NormalizationForm nf, ... array<String^>^ words)
   {
      for (int ctr = 0; ctr < words->Length; ctr++)
         if (! words[ctr]->IsNormalized(nf))
            words[ctr] = words[ctr]->Normalize(nf); 
      return words;   
   }

public: 
   void Execute()
   {
      sw = gcnew StreamWriter(".\\TestNorm1.txt");

      // Define three versions of the same word.  
      String^ s1 = L"sống";        // create word with U+1ED1 
      String^ s2 = L"s\x00F4\x0301ng";
      String^ s3 = L"so\x0302\x0301ng";

      TestForEquality(s1, s2, s3);      
      sw->WriteLine();

      // Normalize and compare strings using each normalization form. 
      for each (String^ formName in Enum::GetNames(NormalizationForm::typeid))
      {
         sw->WriteLine("Normalization {0}:\n", formName); 
         NormalizationForm nf = (NormalizationForm) Enum::Parse(NormalizationForm::typeid, formName);
         array<String^>^ sn = NormalizeStrings(nf, s1, s2, s3 );
         TestForEquality(sn);           
         sw->WriteLine("\n");                                        
      }

      sw->Close(); 
   }
};

void main()
{
   Example^ ex = gcnew Example();
   ex->Execute();
}
// The example produces the following output:
// 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
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 += String.Format("{0} ", Convert.ToUInt16(ch).ToString("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
Imports System.Globalization
Imports System.IO
Imports System.Text

Module Example
   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(&h00F4) + ChrW(&h0301) + "ng"
      Dim s3 As String = "so" + ChrW(&h0302) + ChrW(&h0301) + "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.NormalizationForm,以及Unicode 标准附录 #15: Unicode 范式并且规范化常见问题解答上unicode.org 网站。For more information about normalization and normalization forms, see System.Text.NormalizationForm, as well as Unicode Standard Annex #15: Unicode Normalization Forms and the Normalization FAQ on the unicode.org website.

按类别的字符串操作String operations by category

String类提供用于比较字符串,测试字符串是否相等,查找字符或字符串,修改字符串,提取字符串的组合字符串,格式化值,复制字符串的字符串中子字符串的成员和规范化字符串。The String class provides members for comparing strings, testing strings for equality, finding characters or substrings in a string, modifying a string, extracting substrings from a string, combining strings, formatting values, copying a string, and normalizing a string.

比较字符串Comparing strings

您可以比较字符串来确定二者在排序顺序中的相对位置通过使用以下String方法:You can compare strings to determine their relative position in the sort order by using the following String methods:

  • Compare 返回一个整数,指示一个字符串在排序顺序中第二个字符串的关系。Compare returns an integer that indicates the relationship of one string to a second string in the sort order.

  • CompareOrdinal 返回一个整数,指示一个根据其码位比较的第二个字符串的字符串的关系。CompareOrdinal returns an integer that indicates the relationship of one string to a second string based on a comparison of their code points.

  • CompareTo 返回一个整数,指示当前的字符串实例与第二个字符串在排序顺序中的关系。CompareTo returns an integer that indicates the relationship of the current string instance to a second string in the sort order. CompareTo(String)方法提供IComparableIComparable<T>实现String类。The CompareTo(String) method provides the IComparable and IComparable<T> implementations for the String class.

测试字符串相等Testing strings for equality

在调用Equals方法来确定两个字符串是否相等。You call the Equals method to determine whether two strings are equal. 实例Equals(String, String, StringComparison)和静态Equals(String, StringComparison)重载允许您指定比较是否区分区域性的或序号,以及是否考虑或忽略大小写。The instance Equals(String, String, StringComparison) and the static Equals(String, StringComparison) overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. 为确定相等性的大多数测试是序号,并确定为系统资源 (如文件系统对象) 的访问权限为确定相等性比较应始终为序号。Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal.

查找字符串中的字符Finding characters in a string

String类包括两种类型的搜索方法:The String class includes two kinds of search methods:

警告

如果你想要搜索字符串中的特定模式而不是特定的子字符串,则应使用正则表达式。If you want to search a string for a particular pattern rather than a specific substring, you should use regular expressions. 有关详细信息,请参阅.NET 正则表达式For more information, see .NET Regular Expressions.

修改字符串Modifying a string

String类包括以下方法看起来要修改字符串的值:The String class includes the following methods that appear to modify the value of a string:

  • Insert 将字符串插入到当前String实例。Insert inserts a string into the current String instance.

  • PadLeft 字符串的开头处插入指定字符的一个或多个匹配项。PadLeft inserts one or more occurrences of a specified character at the beginning of a string.

  • PadRight 字符串的末尾处插入指定字符的一个或多个匹配项。PadRight inserts one or more occurrences of a specified character at the end of a string.

  • Remove 删除从当前的子字符串String实例。Remove deletes a substring from the current String instance.

  • Replace 子字符串替换为另一个子字符串在当前String实例。Replace replaces a substring with another substring in the current String instance.

  • ToLowerToLowerInvariant字符串中的所有字符都转换为小写。ToLower and ToLowerInvariant convert all the characters in a string to lowercase.

  • ToUpperToUpperInvariant将字符串中的所有字符都转换为大写。ToUpper and ToUpperInvariant convert all the characters in a string to uppercase.

  • Trim 开始位置和字符串的末尾移除所有空白字符。Trim removes all occurrences of a character from the beginning and end of a string.

  • TrimEnd 删除字符串的末尾出现的所有字符。TrimEnd removes all occurrences of a character from the end of a string.

  • TrimStart 从字符串的开头移除所有空白字符。TrimStart removes all occurrences of a character from the beginning of a string.

重要

所有字符串修改方法都返回一个新String对象。All string modification methods return a new String object. 它们不会修改当前实例的值。They don't modify the value of the current instance.

从字符串中提取子字符串Extracting substrings from a string

String.Split方法将单个字符串拆分为多个字符串。The String.Split method separates a single string into multiple strings. 该方法的重载,可以指定多个分隔符,以确定最大数量的子字符串中提取方法,并确定是否包括在返回的字符串为空字符串 (它是相邻的分隔符时发生)。Overloads of the method allow you to specify multiple delimiters, to determine the maximum number of substrings that the method extracts, and to determine whether empty strings (which occur when delimiters are adjacent) are included among the returned strings.

组合字符串Combining strings

以下String方法可用来进行字符串串联:The following String methods can be used for string concatenation:

  • Concat 将合并成单个字符串的一个或多个子字符串。Concat combines one or more substrings into a single string.

  • Join 将一个或多个到单个元素的子字符串连接在一起,并添加每个子字符串之间的分隔符。Join concatenates one or more substrings into a single element and adds a separator between each substring.

设置值的格式Formatting values

String.Format方法使用复合格式设置功能来在字符串中的一个或多个占位符替换为某些对象或值的字符串表示形式。The String.Format method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. Format方法通常用于执行以下操作:The Format method is often used to do the following:

  • 若要在字符串中嵌入的数字值的字符串表示形式。To embed the string representation of a numeric value in a string.

  • 若要在字符串中嵌入的日期和时间值的字符串表示形式。To embed the string representation of a date and time value in a string.

  • 若要在字符串中嵌入一个枚举值的字符串表示形式。To embed the string representation of an enumeration value in a string.

  • 若要嵌入支持某些对象的字符串表示形式IFormattable字符串中的接口。To embed the string representation of some object that supports the IFormattable interface in a string.

  • 若要从右对齐或左对齐更大的字符串中的字段中的子字符串。To right-justify or left-justify a substring in a field within a larger string.

有关格式设置操作和示例的详细信息,请参阅Format重载摘要。For detailed information about formatting operations and examples, see the Format overload summary.

复制字符串Copying a string

您可以通过调用以下String方法,以便可以字符串的副本:You can call the following String methods to make a copy of a string:

  • Clone 返回对现有的引用String对象。Clone returns a reference to an existing String object.

  • Copy 创建现有字符串的副本。Copy creates a copy of an existing string.

  • CopyTo 将字符串的一部分复制到字符数组。CopyTo copies a portion of a string to a character array.

规范化字符串Normalizing a string

Unicode 字符,单个字符可具有多个代码点。In Unicode, a single character can have multiple code points. 规范化将相同的二进制表示形式转换为这些等效字符。Normalization converts these equivalent characters into the same binary representation. String.Normalize方法执行规范化和String.IsNormalized方法确定是否规范化字符串。The String.Normalize method performs the normalization, and the String.IsNormalized method determines whether a string is normalized.

有关详细信息和示例,请参阅规范化本主题前面的部分。For more information and an example, see the Normalization section earlier in this topic.

构造函数

String(Char*) String(Char*) String(Char*) String(Char*)

String 类的新实例初始化为由指向 Unicode 字符数组的指定指针指示的值。 Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.

String(Char*, Int32, Int32) String(Char*, Int32, Int32) String(Char*, Int32, Int32) String(Char*, Int32, Int32)

String 类的新实例初始化为由指向 Unicode 字符数组的指定指针指示的值、该数组内的起始字符位置和一个长度指示的值。 Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

String(Char, Int32) String(Char, Int32) String(Char, Int32) String(Char, Int32)

String 类的新实例初始化为由重复指定次数的指定 Unicode 字符指示的值。 Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

String(Char[]) String(Char[]) String(Char[]) String(Char[])

String 类的新实例初始化为由 Unicode 字符数组指示的值。 Initializes a new instance of the String class to the value indicated by an array of Unicode characters.

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

String 类的新实例初始化为由 Unicode 字符数组、该数组内的起始字符位置和一个长度指示的值。 Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>)
String(SByte*) String(SByte*) String(SByte*) String(SByte*)

String 类的新实例初始化为由指向 8 位有符号整数数组的指针指示的值。 Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

String(SByte*, Int32, Int32) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32)

String 类的新实例初始化为由指向 8 位有符号整数数组的指定指针、该数组内的起始位置和一个长度指示的值。 Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

String(SByte*, Int32, Int32, Encoding) String(SByte*, Int32, Int32, Encoding) String(SByte*, Int32, Int32, Encoding) String(SByte*, Int32, Int32, Encoding)

String 的新实例初始化为由指向 8 位有符号整数数组的指定指针、该数组内的起始位置、长度以及 Encoding 对象指示的值。 Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

字段

Empty Empty Empty Empty

表示空字符串。 Represents the empty string. 此字段为只读。 This field is read-only.

属性

Chars[Int32] Chars[Int32] Chars[Int32] Chars[Int32]

获取当前 Char 对象中位于指定位置的 String 对象。 Gets the Char object at a specified position in the current String object.

Length Length Length Length

获取当前 String 对象中的字符数。 Gets the number of characters in the current String object.

方法

Clone() Clone() Clone() Clone()

返回对此 String 实例的引用。 Returns a reference to this instance of String.

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

比较两个指定的 String 对象的子字符串,并返回一个指示二者在排序顺序中的相对位置的整数。 Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

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

比较两个指定的 String 对象的子字符串(忽略或考虑其大小写),并返回一个整数,指示二者在排序顺序中的相对位置。 Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

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

比较两个指定的 String 对象(其中忽略或考虑其大小写,并使用区域性特定的信息干预比较),并返回一个整数,指示二者在排序顺序中的相对位置。 Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

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

对两个指定 String 对象的子字符串进行比较,使用指定的比较选项和区域性特定的信息来影响比较,并返回一个整数,该整数指示这两个子字符串在排序顺序中的关系。 Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

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

使用指定的规则比较两个指定的 String 对象的子字符串,并返回一个整数,指示二者在排序顺序中的相对位置。 Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

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

比较两个指定的 String 对象,并返回一个指示二者在排序顺序中的相对位置的整数。 Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

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

比较两个指定的 String 对象(其中忽略或考虑其大小写),并返回一个整数,指示二者在排序顺序中的相对位置。 Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

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

比较两个指定的 String 对象(其中忽略或考虑其大小写,并使用区域性特定的信息干预比较),并返回一个整数,指示二者在排序顺序中的相对位置。 Compares two specified String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

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

对两个指定的 String 对象进行比较,使用指定的比较选项和区域性特定的信息来影响比较,并返回一个整数,该整数指示这两个字符串在排序顺序中的关系。 Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order.

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

使用指定的规则比较两个指定的 String 对象,并返回一个整数,指示二者在排序顺序中的相对位置。 Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

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

通过计算每个子字符串中相应 String 对象的数值来比较两个指定的 Char 对象的子字符串。 Compares substrings of two specified String objects by evaluating the numeric values of the corresponding Char objects in each substring.

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

通过计算每个字符串中相应 String 对象的数值来比较两个指定的 Char 对象。 Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

将此实例与指定的 Object 进行比较,并指示此实例在排序顺序中是位于指定的 Object 之前、之后还是与其出现在同一位置。 Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

CompareTo(String) CompareTo(String) CompareTo(String) CompareTo(String)

将此实例与指定的 String 对象进行比较,并指示此实例在排序顺序中是位于指定的字符串之前、之后还是与其出现在同一位置。 Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.

Concat(IEnumerable<String>) Concat(IEnumerable<String>) Concat(IEnumerable<String>) Concat(IEnumerable<String>)

串联类型为 IEnumerable<T>String 构造集合的成员。 Concatenates the members of a constructed IEnumerable<T> collection of type String.

Concat(Object) Concat(Object) Concat(Object) Concat(Object)

创建指定对象的字符串表示形式。 Creates the string representation of a specified object.

Concat(Object, Object) Concat(Object, Object) Concat(Object, Object) Concat(Object, Object)

连接两个指定对象的字符串表示形式。 Concatenates the string representations of two specified objects.

Concat(Object, Object, Object) Concat(Object, Object, Object) Concat(Object, Object, Object) Concat(Object, Object, Object)

连接三个指定对象的字符串表示形式。 Concatenates the string representations of three specified objects.

Concat(Object, Object, Object, Object) Concat(Object, Object, Object, Object) Concat(Object, Object, Object, Object) Concat(Object, Object, Object, Object)

将四个指定对象的字符串表示形式与可选变量长度参数列表中指定的任何对象串联起来。 Concatenates the string representations of four specified objects and any objects specified in an optional variable length parameter list.

Concat(Object[]) Concat(Object[]) Concat(Object[]) Concat(Object[])

连接指定 Object 数组中的元素的字符串表示形式。 Concatenates the string representations of the elements in a specified Object array.

Concat(String, String) Concat(String, String) Concat(String, String) Concat(String, String)

连接 String 的两个指定实例。 Concatenates two specified instances of String.

Concat(String, String, String) Concat(String, String, String) Concat(String, String, String) Concat(String, String, String)

连接 String 的三个指定实例。 Concatenates three specified instances of String.

Concat(String, String, String, String) Concat(String, String, String, String) Concat(String, String, String, String) Concat(String, String, String, String)

连接 String 的四个指定实例。 Concatenates four specified instances of String.

Concat(String[]) Concat(String[]) Concat(String[]) Concat(String[])

连接指定的 String 数组的元素。 Concatenates the elements of a specified String array.

Concat<T>(IEnumerable<T>) Concat<T>(IEnumerable<T>) Concat<T>(IEnumerable<T>) Concat<T>(IEnumerable<T>)

串联 IEnumerable<T> 实现的成员。 Concatenates the members of an IEnumerable<T> implementation.

Contains(Char) Contains(Char) Contains(Char) Contains(Char)
Contains(Char, StringComparison) Contains(Char, StringComparison) Contains(Char, StringComparison) Contains(Char, StringComparison)
Contains(String) Contains(String) Contains(String) Contains(String)

返回一个值,该值指示指定的子串是否出现在此字符串中。 Returns a value indicating whether a specified substring occurs within this string.

Contains(String, StringComparison) Contains(String, StringComparison) Contains(String, StringComparison) Contains(String, StringComparison)
Copy(String) Copy(String) Copy(String) Copy(String)

创建一个与指定的 String 具有相同值的 String 的新实例。 Creates a new instance of String with the same value as a specified String.

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

将指定数目的字符从此实例中的指定位置复制到 Unicode 字符数组中的指定位置。 Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.

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

确定此字符串实例的结尾是否与指定的字符串匹配。 Determines whether the end of this string instance matches the specified string.

EndsWith(String, Boolean, CultureInfo) EndsWith(String, Boolean, CultureInfo) EndsWith(String, Boolean, CultureInfo) EndsWith(String, Boolean, CultureInfo)

确定在使用指定的区域性进行比较时此字符串实例的结尾是否与指定的字符串匹配。 Determines whether the end of this string instance matches the specified string when compared using the specified culture.

EndsWith(String, StringComparison) EndsWith(String, StringComparison) EndsWith(String, StringComparison) EndsWith(String, StringComparison)

确定使用指定的比较选项进行比较时此字符串实例的结尾是否与指定的字符串匹配。 Determines whether the end of this string instance matches the specified string when compared using the specified comparison option.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定此实例是否与指定的对象(也必须是 String 对象)具有相同的值。 Determines whether this instance and a specified object, which must also be a String object, have the same value.

Equals(String) Equals(String) Equals(String) Equals(String)

确定此实例是否与另一个指定的 String 对象具有相同的值。 Determines whether this instance and another specified String object have the same value.

Equals(String, String) Equals(String, String) Equals(String, String) Equals(String, String)

确定两个指定的 String 对象是否具有相同的值。 Determines whether two specified String objects have the same value.

Equals(String, String, StringComparison) Equals(String, String, StringComparison) Equals(String, String, StringComparison) Equals(String, String, StringComparison)

确定两个指定的 String 对象是否具有相同的值。 Determines whether two specified String objects have the same value. 参数指定区域性、大小写以及比较所用的排序规则。 A parameter specifies the culture, case, and sort rules used in the comparison.

Equals(String, StringComparison) Equals(String, StringComparison) Equals(String, StringComparison) Equals(String, StringComparison)

确定此字符串是否与另一个指定的 String 对象具有相同的值。 Determines whether this string and a specified String object have the same value. 参数指定区域性、大小写以及比较所用的排序规则。 A parameter specifies the culture, case, and sort rules used in the comparison.

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

将指定字符串中的一个或多个格式项替换为对应对象的字符串表示形式。 Replaces the format item or items in a specified string with the string representation of the corresponding object. 参数提供区域性特定的格式设置信息。 A parameter supplies culture-specific formatting information.

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

将字符串中的格式项替换为两个指定对象的字符串表示形式。 Replaces the format items in a string with the string representation of two specified objects. 参数提供区域性特定的格式设置信息。 A parameter supplies culture-specific formatting information.

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

将字符串中的格式项替换为三个指定对象的字符串表示形式。 Replaces the format items in a string with the string representation of three specified objects. 参数提供区域性特定的格式设置信息。 An parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[])

将字符串中的格式项替换为指定数组中相应对象的字符串表示形式。 Replaces the format items in a string with the string representations of corresponding objects in a specified array. 参数提供区域性特定的格式设置信息。 A parameter supplies culture-specific formatting information.

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

将字符串中的一个或多个格式项替换为指定对象的字符串表示形式。 Replaces one or more format items in a string with the string representation of a specified object.

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

将字符串中的格式项替换为两个指定对象的字符串表示形式。 Replaces the format items in a string with the string representation of two specified objects.

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

将字符串中的格式项替换为三个指定对象的字符串表示形式。 Replaces the format items in a string with the string representation of three specified objects.

Format(String, Object[]) Format(String, Object[]) Format(String, Object[]) Format(String, Object[])

将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。 Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

检索一个可以循环访问此字符串中的每个字符的对象。 Retrieves an object that can iterate through the individual characters in this string.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回该字符串的哈希代码。 Returns the hash code for this string.

GetHashCode(StringComparison) GetHashCode(StringComparison) GetHashCode(StringComparison) GetHashCode(StringComparison)
GetType() GetType() GetType() GetType()

获取当前实例的 Type Gets the Type of the current instance.

(Inherited from Object)
GetTypeCode() GetTypeCode() GetTypeCode() GetTypeCode()

返回类 TypeCodeString Returns the TypeCode for class String.

IndexOf(Char) IndexOf(Char) IndexOf(Char) IndexOf(Char)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified Unicode character in this string. 该搜索从指定字符位置开始。 The search starts at a specified character position.

IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32)

报告指定字符在此实例中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified character in this instance. 搜索从指定字符位置开始,并检查指定数量的字符位置。 The search starts at a specified character position and examines a specified number of character positions.

IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison)
IndexOf(String) IndexOf(String) IndexOf(String) IndexOf(String)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified string in this instance.

IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified string in this instance. 该搜索从指定字符位置开始。 The search starts at a specified character position.

IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified string in this instance. 搜索从指定字符位置开始,并检查指定数量的字符位置。 The search starts at a specified character position and examines a specified number of character positions.

IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified string in the current String object. 参数指定当前字符串中的起始搜索位置、要搜索的当前字符串中的字符数量,以及要用于指定字符串的搜索类型。 Parameters specify the starting search position in the current string, the number of characters in the current string to search, and the type of search to use for the specified string.

IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified string in the current String object. 参数指定当前字符串中的起始搜索位置以及用于指定字符串的搜索类型。 Parameters specify the starting search position in the current string and the type of search to use for the specified string.

IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence of the specified string in the current String object. 一个参数指定要用于指定字符串的搜索类型。 A parameter specifies the type of search to use for the specified string.

IndexOfAny(Char[]) IndexOfAny(Char[]) IndexOfAny(Char[]) IndexOfAny(Char[])

报告指定 Unicode 字符数组中的任意字符在此实例中第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

IndexOfAny(Char[], Int32) IndexOfAny(Char[], Int32) IndexOfAny(Char[], Int32) IndexOfAny(Char[], Int32)

报告指定 Unicode 字符数组中的任意字符在此实例中第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 该搜索从指定字符位置开始。 The search starts at a specified character position.

IndexOfAny(Char[], Int32, Int32) IndexOfAny(Char[], Int32, Int32) IndexOfAny(Char[], Int32, Int32) IndexOfAny(Char[], Int32, Int32)

报告指定 Unicode 字符数组中的任意字符在此实例中第一个匹配项的从零开始的索引。 Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 搜索从指定字符位置开始,并检查指定数量的字符位置。 The search starts at a specified character position and examines a specified number of character positions.

Insert(Int32, String) Insert(Int32, String) Insert(Int32, String) Insert(Int32, String)

返回一个新的字符串,在此实例中的指定的索引位置插入指定的字符串。 Returns a new string in which a specified string is inserted at a specified index position in this instance.

Intern(String) Intern(String) Intern(String) Intern(String)

检索系统对指定 String 的引用。 Retrieves the system's reference to the specified String.

IsInterned(String) IsInterned(String) IsInterned(String) IsInterned(String)

检索对指定 String 的引用。 Retrieves a reference to a specified String.

IsNormalized() IsNormalized() IsNormalized() IsNormalized()

指示此字符串是否符合 Unicode 范式 C。 Indicates whether this string is in Unicode normalization form C.

IsNormalized(NormalizationForm) IsNormalized(NormalizationForm) IsNormalized(NormalizationForm) IsNormalized(NormalizationForm)

指示此字符串是否符合指定的 Unicode 范式。 Indicates whether this string is in the specified Unicode normalization form.

IsNullOrEmpty(String) IsNullOrEmpty(String) IsNullOrEmpty(String) IsNullOrEmpty(String)

指示指定的字符串是 null 还是 Empty 字符串。 Indicates whether the specified string is null or an Empty string.

IsNullOrWhiteSpace(String) IsNullOrWhiteSpace(String) IsNullOrWhiteSpace(String) IsNullOrWhiteSpace(String)

指示指定的字符串是 null、空还是仅由空白字符组成。 Indicates whether a specified string is null, empty, or consists only of white-space characters.

Join(Char, Object[]) Join(Char, Object[]) Join(Char, Object[]) Join(Char, Object[])
Join(Char, String[]) Join(Char, String[]) Join(Char, String[]) Join(Char, String[])
Join(Char, String[], Int32, Int32) Join(Char, String[], Int32, Int32) Join(Char, String[], Int32, Int32) Join(Char, String[], Int32, Int32)
Join(String, IEnumerable<String>) Join(String, IEnumerable<String>) Join(String, IEnumerable<String>) Join(String, IEnumerable<String>)

串联类型为 IEnumerable<T>String 构造集合的成员,其中在每个成员之间使用指定的分隔符。 Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member.

Join(String, Object[]) Join(String, Object[]) Join(String, Object[]) Join(String, Object[])

串联对象数组的各个元素,其中在每个元素之间使用指定的分隔符。 Concatenates the elements of an object array, using the specified separator between each element.

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

串联字符串数组的所有元素,其中在每个元素之间使用指定的分隔符。 Concatenates all the elements of a string array, using the specified separator between each element.

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

串联字符串数组的指定元素,其中在每个元素之间使用指定的分隔符。 Concatenates the specified elements of a string array, using the specified separator between each element.

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

串联集合的成员,其中在每个成员之间使用指定的分隔符。 Concatenates the members of a collection, using the specified separator between each member.

LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char)

报告指定 Unicode 字符在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.

LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32)

报告指定 Unicode 字符在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. 在指定的字符位置开始和在向后的右边该字符串的开头处理的搜索。 The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32)

报告指定的 Unicode 字符在此实例内的子字符串中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring within this instance. 搜索在指定字符位置的数目的字符串开始时,开始指定字符和其后面的位置。 The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String) LastIndexOf(String) LastIndexOf(String) LastIndexOf(String)

报告指定字符串在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of a specified string within this instance.

LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32)

报告指定字符串在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of a specified string within this instance. 在指定的字符位置开始和在向后的右边该字符串的开头处理的搜索。 The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32)

报告指定字符串在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of a specified string within this instance. 搜索在指定字符位置的数目的字符串开始时,开始指定字符和其后面的位置。 The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison)

报告指定字符串在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence of a specified string within this instance. 搜索在所指定的字符位置的数目的字符串开始时,开始指定字符和其后面的位置。 The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. 一个参数指定要执行搜索指定字符串的比较类型。 A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison)

报告指定字符串在当前 String 对象中最后一个匹配项的从零开始的索引。 Reports the zero-based index of the last occurrence of a specified string within the current String object. 在指定的字符位置开始和在向后的右边该字符串的开头处理的搜索。 The search starts at a specified character position and proceeds backward toward the beginning of the string. 一个参数指定要执行搜索指定字符串的比较类型。 A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison)

报告指定字符串在当前 String 对象中最后一个匹配项的从零开始的索引。 Reports the zero-based index of the last occurrence of a specified string within the current String object. 一个参数指定要用于指定字符串的搜索类型。 A parameter specifies the type of search to use for the specified string.

LastIndexOfAny(Char[]) LastIndexOfAny(Char[]) LastIndexOfAny(Char[]) LastIndexOfAny(Char[])

报告在 Unicode 数组中指定的一个或多个字符在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array.

LastIndexOfAny(Char[], Int32) LastIndexOfAny(Char[], Int32) LastIndexOfAny(Char[], Int32) LastIndexOfAny(Char[], Int32)

报告在 Unicode 数组中指定的一个或多个字符在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. 在指定的字符位置开始和在向后的右边该字符串的开头处理的搜索。 The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOfAny(Char[], Int32, Int32) LastIndexOfAny(Char[], Int32, Int32) LastIndexOfAny(Char[], Int32, Int32) LastIndexOfAny(Char[], Int32, Int32)

报告在 Unicode 数组中指定的一个或多个字符在此实例中的最后一个匹配项的从零开始的索引的位置。 Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. 搜索在指定字符位置的数目的字符串开始时,开始指定字符和其后面的位置。 The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。 Creates a shallow copy of the current Object.

(Inherited from Object)
Normalize() Normalize() Normalize() Normalize()

返回一个新字符串,其文本值与此字符串相同,但其二进制表示形式符合 Unicode 范式 C。 Returns a new string whose textual value is the same as this string, but whose binary representation is in Unicode normalization form C.

Normalize(NormalizationForm) Normalize(NormalizationForm) Normalize(NormalizationForm) Normalize(NormalizationForm)

返回一个新字符串,其文本值与此字符串相同,但其二进制表示形式符合指定的 Unicode 范式。 Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form.

PadLeft(Int32) PadLeft(Int32) PadLeft(Int32) PadLeft(Int32)

返回一个新字符串,该字符串通过在此实例中的字符左侧填充空格来达到指定的总长度,从而实现右对齐。 Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length.

PadLeft(Int32, Char) PadLeft(Int32, Char) PadLeft(Int32, Char) PadLeft(Int32, Char)

返回一个新字符串,该字符串通过在此实例中的字符左侧填充指定的 Unicode 字符来达到指定的总长度,从而使这些字符右对齐。 Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.

PadRight(Int32) PadRight(Int32) PadRight(Int32) PadRight(Int32)

返回一个新字符串,该字符串通过在此字符串中的字符右侧填充空格来达到指定的总长度,从而使这些字符左对齐。 Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

PadRight(Int32, Char) PadRight(Int32, Char) PadRight(Int32, Char) PadRight(Int32, Char)

返回一个新字符串,该字符串通过在此字符串中的字符右侧填充指定的 Unicode 字符来达到指定的总长度,从而使这些字符左对齐。 Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.

Remove(Int32) Remove(Int32) Remove(Int32) Remove(Int32)

返回当前实例中从指定位置到最后位置的所有以删除的字符的新字符串。 Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.

Remove(Int32, Int32) Remove(Int32, Int32) Remove(Int32, Int32) Remove(Int32, Int32)

返回指定数量字符在当前这个实例起始点在已删除的指定的位置的新字符串。 Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

Replace(Char, Char) Replace(Char, Char) Replace(Char, Char) Replace(Char, Char)

返回一个新字符串,其中此实例中出现的所有指定 Unicode 字符都替换为另一个指定的 Unicode 字符。 Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.

Replace(String, String) Replace(String, String) Replace(String, String) Replace(String, String)

返回一个新字符串,其中当前实例中出现的所有指定字符串都替换为另一个指定的字符串。 Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Replace(String, String, Boolean, CultureInfo) Replace(String, String, Boolean, CultureInfo) Replace(String, String, Boolean, CultureInfo) Replace(String, String, Boolean, CultureInfo)
Replace(String, String, StringComparison) Replace(String, String, StringComparison) Replace(String, String, StringComparison) Replace(String, String, StringComparison)
Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)
Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)
Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

基于数组中的字符将字符串拆分为多个子字符串。 Splits a string into substrings that are based on the characters in an array.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

基于数组中的字符将一个字符串拆分成最大数量的子字符串。 Splits a string into a maximum number of substrings based on the characters in an array. 也可指定要返回的子字符串的最大数量。 You also specify the maximum number of substrings to return.

Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

基于数组中的字符将一个字符串拆分成最大数量的子字符串。 Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

基于数组中的字符将字符串拆分为多个子字符串。 Splits a string into substrings based on the characters in an array. 可以指定子字符串是否包含空数组元素。 You can specify whether the substrings include empty array elements.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)
Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)
Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

基于数组中的字符串将一个字符串拆分成最大数量的子字符串。 Splits a string into a maximum number of substrings based on the strings in an array. 可以指定子字符串是否包含空数组元素。 You can specify whether the substrings include empty array elements.

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

基于数组中的字符串将字符串拆分为多个子字符串。 Splits a string into substrings based on the strings in an array. 可以指定子字符串是否包含空数组元素。 You can specify whether the substrings include empty array elements.

StartsWith(Char) StartsWith(Char) StartsWith(Char) StartsWith(Char)
StartsWith(String) StartsWith(String) StartsWith(String) StartsWith(String)

确定此字符串实例的开头是否与指定的字符串匹配。 Determines whether the beginning of this string instance matches the specified string.

StartsWith(String, Boolean, CultureInfo) StartsWith(String, Boolean, CultureInfo) StartsWith(String, Boolean, CultureInfo) StartsWith(String, Boolean, CultureInfo)

确定在使用指定的区域性进行比较时此字符串实例的开头是否与指定的字符串匹配。 Determines whether the beginning of this string instance matches the specified string when compared using the specified culture.

StartsWith(String, StringComparison) StartsWith(String, StringComparison) StartsWith(String, StringComparison) StartsWith(String, StringComparison)

确定在使用指定的比较选项进行比较时此字符串实例的开头是否与指定的字符串匹配。 Determines whether the beginning of this string instance matches the specified string when compared using the specified comparison option.

Substring(Int32) Substring(Int32) Substring(Int32) Substring(Int32)

从此实例检索子字符串。 Retrieves a substring from this instance. 子字符串在指定的字符位置开始并一直到该字符串的末尾。 The substring starts at a specified character position and continues to the end of the string.

Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32)

从此实例检索子字符串。 Retrieves a substring from this instance. 子字符串从指定的字符位置开始且具有指定的长度。 The substring starts at a specified character position and has a specified length.

ToCharArray() ToCharArray() ToCharArray() ToCharArray()

将此实例中的字符复制到 Unicode 字符数组。 Copies the characters in this instance to a Unicode character array.

ToCharArray(Int32, Int32) ToCharArray(Int32, Int32) ToCharArray(Int32, Int32) ToCharArray(Int32, Int32)

将此实例中的指定子字符串内的字符复制到 Unicode 字符数组。 Copies the characters in a specified substring in this instance to a Unicode character array.

ToLower() ToLower() ToLower() ToLower()

返回此字符串转换为小写形式的副本。 Returns a copy of this string converted to lowercase.

ToLower(CultureInfo) ToLower(CultureInfo) ToLower(CultureInfo) ToLower(CultureInfo)

根据指定区域性的大小写规则返回此字符串转换为小写形式的副本。 Returns a copy of this string converted to lowercase, using the casing rules of the specified culture.

ToLowerInvariant() ToLowerInvariant() ToLowerInvariant() ToLowerInvariant()

返回此 String 对象的转换为小写形式的副本,返回时使用固定区域性的大小写规则。 Returns a copy of this String object converted to lowercase using the casing rules of the invariant culture.

ToString() ToString() ToString() ToString()

返回 String 的此实例;不执行实际转换。 Returns this instance of String; no actual conversion is performed.

ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider)

返回 String 的此实例;不执行实际转换。 Returns this instance of String; no actual conversion is performed.

ToUpper() ToUpper() ToUpper() ToUpper()

返回此字符串转换为大写形式的副本。 Returns a copy of this string converted to uppercase.

ToUpper(CultureInfo) ToUpper(CultureInfo) ToUpper(CultureInfo) ToUpper(CultureInfo)

根据指定区域性的大小写规则返回此字符串转换为大写形式的副本。 Returns a copy of this string converted to uppercase, using the casing rules of the specified culture.

ToUpperInvariant() ToUpperInvariant() ToUpperInvariant() ToUpperInvariant()

返回此 String 对象的转换为大写形式的副本,返回时使用固定区域性的大小写规则。 Returns a copy of this String object converted to uppercase using the casing rules of the invariant culture.

Trim() Trim() Trim() Trim()

从当前 String 对象移除所有前导空白字符和尾部空白字符。 Removes all leading and trailing white-space characters from the current String object.

Trim(Char) Trim(Char) Trim(Char) Trim(Char)
Trim(Char[]) Trim(Char[]) Trim(Char[]) Trim(Char[])

从当前 String 对象移除数组中指定的一组字符的所有前导匹配项和尾部匹配项。 Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.

TrimEnd() TrimEnd() TrimEnd() TrimEnd()
TrimEnd(Char) TrimEnd(Char) TrimEnd(Char) TrimEnd(Char)
TrimEnd(Char[]) TrimEnd(Char[]) TrimEnd(Char[]) TrimEnd(Char[])

从当前 String 对象移除数组中指定的一组字符的所有尾部匹配项。 Removes all trailing occurrences of a set of characters specified in an array from the current String object.

TrimStart() TrimStart() TrimStart() TrimStart()
TrimStart(Char) TrimStart(Char) TrimStart(Char) TrimStart(Char)
TrimStart(Char[]) TrimStart(Char[]) TrimStart(Char[]) TrimStart(Char[])

从当前 String 对象移除数组中指定的一组字符的所有前导匹配项。 Removes all leading occurrences of a set of characters specified in an array from the current String object.

操作员

Equality(String, String) Equality(String, String) Equality(String, String) Equality(String, String)

确定两个指定的字符串是否具有相同的值。 Determines whether two specified strings have the same value.

Implicit(String to ReadOnlySpan<Char>) Implicit(String to ReadOnlySpan<Char>) Implicit(String to ReadOnlySpan<Char>) Implicit(String to ReadOnlySpan<Char>)
Inequality(String, String) Inequality(String, String) Inequality(String, String) Inequality(String, String)

确定两个指定的字符串是否具有不同的值。 Determines whether two specified strings have different values.

显式界面实现

IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)
IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider)

有关此成员的说明,请参阅 ToBoolean(IFormatProvider) For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider)

有关此成员的说明,请参阅 ToByte(IFormatProvider) For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider)

有关此成员的说明,请参阅 ToChar(IFormatProvider) For a description of this member, see ToChar(IFormatProvider).

IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider)

有关此成员的说明,请参阅 ToDateTime(IFormatProvider) For a description of this member, see ToDateTime(IFormatProvider).

IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider)

有关此成员的说明,请参阅 ToDecimal(IFormatProvider) For a description of this member, see ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider)

有关此成员的说明,请参阅 ToDouble(IFormatProvider) For a description of this member, see ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider)

有关此成员的说明,请参阅 ToInt16(IFormatProvider) For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider)

有关此成员的说明,请参阅 ToInt32(IFormatProvider) For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider)

有关此成员的说明,请参阅 ToInt64(IFormatProvider) For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider)

有关此成员的说明,请参阅 ToSByte(IFormatProvider) For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider)

有关此成员的说明,请参阅 ToSingle(IFormatProvider) For a description of this member, see ToSingle(IFormatProvider).

IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider)
IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider)

有关此成员的说明,请参阅 ToType(Type, IFormatProvider) For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider)

有关此成员的说明,请参阅 ToUInt16(IFormatProvider) For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider)

有关此成员的说明,请参阅 ToUInt32(IFormatProvider) For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider)

有关此成员的说明,请参阅 ToUInt64(IFormatProvider) For a description of this member, see ToUInt64(IFormatProvider).

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回循环访问当前 String 对象的枚举数。 Returns an enumerator that iterates through the current String object.

IEnumerable<Char>.GetEnumerator() IEnumerable<Char>.GetEnumerator() IEnumerable<Char>.GetEnumerator() IEnumerable<Char>.GetEnumerator()

返回循环访问当前 String 对象的枚举数。 Returns an enumerator that iterates through the current String object.

适用于

线程安全性

此类型是线程安全的。 This type is thread safe.

另请参阅