String クラス

定義

テキストを一連の UTF-16 コード単位として表現します。

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

注釈

文字列は、テキストを表すために使用される文字のシーケンシャル コレクションです。 Stringオブジェクトは、文字列を表すオブジェクトのSystem.Charシーケンシャル コレクションです。オブジェクトは System.Char UTF-16 コード単位に対応します。 オブジェクトの String 値は、オブジェクトのシーケンシャル コレクションの System.Char 内容であり、その値は不変です (つまり、読み取り専用です)。 文字列の不変性の詳細については、「不変 性」および「StringBuilder クラス 」セクションを参照してください。 メモリ内のオブジェクトの String 最大サイズは 2 GB、つまり約 10 億文字です。

Unicode、UTF-16、コード単位、コード ポイント、および CharRune 型の詳細については、「 .NET での文字エンコードの概要」を参照してください。

このセクションの内容:

String オブジェクトをインスタンス化する
Char オブジェクトと Unicode 文字
文字列と Unicode 標準
文字列と埋め込み null 文字
文字列とインデックス
null 文字列と空の文字列
不変性と StringBuilder クラス
序数とカルチャに依存する操作
正規化
カテゴリ別の文字列操作

String オブジェクトをインスタンス化する

オブジェクトは String 、次の方法でインスタンス化できます。

  • 変数に文字列リテラル String を割り当てること。 これは、文字列を作成するために最も一般的に使用される方法です。 次の例では、代入を使用して複数の文字列を作成します。 C# と F# では、円記号 (\) はエスケープ文字であるため、文字列内のリテラル円記号をエスケープするか、文字列全体を @-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
    
    let string1 = "This is a string created by assignment."
    printfn "%s" string1
    let string2a = "The path is C:\\PublicDocuments\\Report1.doc"
    printfn "%s" string2a
    let string2b = @"The path is C:\PublicDocuments\Report1.doc"
    printfn "%s" string2b
    // The example displays the following output:
    //       This is a string created by assignment.
    //       The path is C:\PublicDocuments\Report1.doc
    //       The path is C:\PublicDocuments\Report1.doc
    
    Dim string1 As String = "This is a string created by assignment."
    Console.WriteLine(string1)
    Dim string2 As String = "The path is C:\PublicDocuments\Report1.doc"
    Console.WriteLine(string2)
    ' The example displays the following output:
    '       This is a string created by assignment.
    '       The path is C:\PublicDocuments\Report1.doc
    
  • クラス コンストラクターを String 呼び出す。 次の例では、複数のクラス コンストラクターを呼び出して文字列をインスタンス化します。 一部のコンストラクターには、文字配列または符号付きバイト配列へのポインターがパラメーターとして含まれることに注意してください。 Visual Basic では、これらのコンストラクターの呼び出しはサポートされていません。 コンストラクターの詳細については、コンストラクターの概要に関 String するページを String 参照してください。

    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
    
    let chars = [| 'w'; 'o'; 'r'; 'd' |]
    let bytes = [| 0x41y; 0x42y; 0x43y; 0x44y; 0x45y; 0x00y |]
    
    // Create a string from a character array.
    let string1 = String chars
    printfn "%s" string1
    
    // Create a string that consists of a character repeated 20 times.
    let string2 = String('c', 20)
    printfn "%s" string2
    
    let stringFromBytes =
        // Create a string from a pointer to a signed byte array.
        use pbytes = fixed bytes
        String pbytes
    let stringFromChars = 
        // Create a string from a pointer to a character array.
        use pchars = fixed chars
        String pchars
    
    printfn $"{stringFromBytes}"
    printfn $"{stringFromChars}"
    // The example displays the following output:
    //       word
    //       cccccccccccccccccccc
    //       ABCDE
    //       word
    
    Dim chars() As Char = { "w"c, "o"c, "r"c, "d"c }
    
    ' Create a string from a character array.
    Dim string1 As New String(chars)
    Console.WriteLine(string1)
    
    ' Create a string that consists of a character repeated 20 times.
    Dim string2 As New String("c"c, 20)
    Console.WriteLine(string2)
    ' The example displays the following output:
    '       word
    '       cccccccccccccccccccc
    
  • 文字列連結演算子 (C# と F# では +、Visual Basic では +) を使用して、 & インスタンスと文字列リテラルの任意の String 組み合わせから 1 つの文字列を作成します。 次の例は、文字列連結演算子の使用方法を示しています。

    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.
    
    let string1 = "Today is " + DateTime.Now.ToString("D") + "."
    printfn $"{string1}"
    
    let string2 = "This is one sentence. " + "This is a second. "
    let string2 = string2 + "This is a third sentence."
    printfn $"{string2}"
    // The example displays output like the following:
    //    Today is Tuesday, July 06, 2011.
    //    This is one sentence. This is a second. This is a third sentence.
    
    Dim string1 As String = "Today is " + Date.Now.ToString("D") + "."  
    Console.WriteLine(string1)
    Dim string2 As String = "This is one sentence. " + "This is a second. "
    string2 += "This is a third sentence."
    Console.WriteLine(string2)      
    ' The example displays output like the following:
    '    Today is Tuesday, July 06, 2011.
    '    This is one sentence. This is a second. This is a third sentence.
    
  • プロパティを取得するか、文字列を返すメソッドを呼び出します。 次の例では、 クラスの メソッドを String 使用して、大きな文字列から部分文字列を抽出します。

    String^ sentence = "This sentence has five words.";
    // Extract the second word.
    int startPosition = sentence->IndexOf(" ") + 1;
    String^ word2 = sentence->Substring(startPosition, 
                                        sentence->IndexOf(" ", startPosition) - startPosition);
    Console::WriteLine("Second word: " + word2);
    
    string sentence = "This sentence has five words.";
    // Extract the second word.
    int startPosition = sentence.IndexOf(" ") + 1;
    string word2 = sentence.Substring(startPosition,
                                      sentence.IndexOf(" ", startPosition) - startPosition);
    Console.WriteLine("Second word: " + word2);
    // The example displays the following output:
    //       Second word: sentence
    
    let sentence = "This sentence has five words."
    // Extract the second word.
    let startPosition = sentence.IndexOf " " + 1
    let word2 = 
        sentence.Substring(startPosition, sentence.IndexOf(" ", startPosition) - startPosition)
    printfn $"Second word: {word2}"
    // The example displays the following output:
    //       Second word: sentence
    
    Dim sentence As String = "This sentence has five words."
    ' Extract the second word.
    Dim startPosition As Integer = sentence.IndexOf(" ") + 1
    Dim word2 As String = sentence.Substring(startPosition, 
                                             sentence.IndexOf(" ", startPosition) - startPosition) 
    Console.WriteLine("Second word: " + word2)
    ' The example displays the following output:
    '       Second word: sentence
    
  • 書式設定メソッドを呼び出して、値またはオブジェクトを文字列表現に変換します。 次の例では、 複合書式設定機能を 使用して、2 つのオブジェクトの文字列表現を文字列に埋め込みます。

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

Char オブジェクトと Unicode 文字

文字列内の各文字は、Unicode コード ポイントまたは Unicode 文字の序数 (数値) 値とも呼ばれる Unicode スカラー値によって定義されます。 各コード ポイントは UTF-16 エンコードを使用してエンコードされ、エンコードの各要素の数値は オブジェクトによって Char 表されます。

注意

インスタンスは UTF-16 コード単位のシーケンシャル コレクションで構成されるため String 、整形式の Unicode 文字列ではないオブジェクトを作成 String できます。 たとえば、対応する高サロゲートを使用せずに、低いサロゲートを持つ文字列を作成できます。 名前空間内 System.Text のオブジェクトをエンコードおよびデコードするメソッドなどの一部のメソッドでは、文字列が整形式であることを確認するためのチェックが実行される場合がありますが、 String クラス メンバーは文字列が整形式であることを確認しません。

通常、1 つの Char オブジェクトは 1 つのコード ポイントを表します。つまり、 の Char 数値はコード ポイントと等しくなります。 たとえば、文字 "a" のコード ポイントは U+0061 です。 ただし、コード ポイントには、複数のエンコードされた要素 (複数の Char オブジェクト) が必要になる場合があります。 Unicode 標準では、複数 Char のオブジェクトに対応する 2 種類の文字 (graphemes と Unicode 補助プレーンの文字に対応する Unicode 補助コード ポイント) が定義されています。

  • Grapheme は、基本文字の後に 1 つ以上の結合文字が続いて表されます。 たとえば、文字 ä は、コード ポイントが U+0061 のオブジェクトの後Charに、コード ポイントが U+0308 であるオブジェクトでChar表されます。 この文字は、U+00E4 のコード ポイントを持つ 1 つの Char オブジェクトでも定義できます。 次の例に示すように、カルチャに依存した等値比較では、通常の序数比較では等しくないものの、これら 2 つの表現が等しいことを示しています。 ただし、2 つの文字列が正規化されている場合、序数比較は等しいことを示します。 (文字列の正規化の詳細については、「 正規化 」セクションを参照してください)。

    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
    
    open System
    open System.IO
    
    do
        use sw = new StreamWriter(@".\graphemes.txt")
        let grapheme = "\u0061\u0308"
        sw.WriteLine grapheme
    
        let singleChar = "\u00e4"
        sw.WriteLine singleChar
    
        sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                    String.Equals(grapheme, singleChar,
                                    StringComparison.CurrentCulture))
        sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar,
                    String.Equals(grapheme, singleChar,
                                    StringComparison.Ordinal))
        sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar,
                    String.Equals(grapheme.Normalize(),
                                    singleChar.Normalize(),
                                    StringComparison.Ordinal))
    // The example produces the following output:
    //       ä
    //       ä
    //       ä = ä (Culture-sensitive): True
    //       ä = ä (Ordinal): False
    //       ä = ä (Normalized Ordinal): True
    
    Imports System.Globalization
    Imports System.IO
    
    Module 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
    
  • Unicode 補助コード ポイント (サロゲート ペア) は、コード ポイントが上位サロゲートであるオブジェクトの CharChar に、コード ポイントが低サロゲートであるオブジェクトによって表されます。 上位サロゲートのコード単位は、U+D800 から U+DBFF の範囲です。 低サロゲートのコード単位は、U+DC00 から U+DFFF の範囲です。 サロゲート ペアは、16 個の Unicode 補助プレーンの文字を表すために使用されます。 次の例では、サロゲート文字を作成し、それを メソッドに渡して Char.IsSurrogatePair(Char, Char) 、サロゲート ペアであるかどうかを判断します。

    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
    
    string surrogate = "\uD800\uDC03";
    for (int ctr = 0; ctr < surrogate.Length; ctr++) 
       Console.Write($"U+{(ushort)surrogate[ctr]:X2} ");
    
    Console.WriteLine();
    Console.WriteLine("   Is Surrogate Pair: {0}", 
                      Char.IsSurrogatePair(surrogate[0], surrogate[1]));
    // The example displays the following output:
    //       U+D800 U+DC03
    //          Is Surrogate Pair: True
    
    open System
    
    let surrogate = "\uD800\uDC03"
    for i = 0 to surrogate.Length - 1 do
        printf $"U+{uint16 surrogate[i]:X2} "
    
    printfn $"\n   Is Surrogate Pair: {Char.IsSurrogatePair(surrogate[0], surrogate[1])}"
    // The example displays the following output:
    //       U+D800 U+DC03
    //          Is Surrogate Pair: True
    
    Module 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 標準

文字列内の文字は、値に対応 Char する UTF-16 でエンコードされたコード単位で表されます。

文字列内の各文字には、列挙によって UnicodeCategory .NET で表される Unicode 文字カテゴリが関連付けられています。 文字またはサロゲート ペアのカテゴリは、 メソッドを CharUnicodeInfo.GetUnicodeCategory 呼び出すことによって決定できます。

.NET は独自の文字のテーブルとそれに対応するカテゴリを保持するため、さまざまなプラットフォームで実行されている特定のバージョンの .NET 実装で同一の文字カテゴリの情報が返されるようになります。 すべての .NET バージョンおよびすべての OS プラットフォームで、文字カテゴリ情報は Unicode 文字データベースによって提供されます。

次の表は、.NET のバージョンとその文字カテゴリが基準としている Unicode 標準のバージョンを示しています。

.NET バージョン Unicode 標準のバージョン
.NET Framework 1.1 Unicode 標準、バージョン 4.0.0
.NET Framework 2.0 Unicode 標準、バージョン 5.0.0
.NET Framework 3.5 Unicode 標準、バージョン 5.0.0
.NET Framework 4 Unicode 標準、バージョン 5.0.0
.NET Framework 4.5 Unicode 標準、バージョン 6.3.0
.NET Framework 4.5.1 Unicode 標準、バージョン 6.3.0
.NET Framework 4.5.2 Unicode 標準、バージョン 6.3.0
.NET Framework 4.6 Unicode 標準、バージョン 6.3.0
.NET Framework 4.6.1 Unicode 標準、バージョン 6.3.0
.NET Framework 4.6.2 およびそれ以降のバージョン Unicode 標準、バージョン 8.0.0
.NET Core 2.1 Unicode 標準、バージョン 8.0.0
.NET Core 3.1 Unicode 標準バージョン 11.0.0
.NET 5 Unicode 標準バージョン 13.0.0

さらに、.NET では、Unicode 標準に基づく文字列の比較と並べ替えがサポートされています。 .NET Framework 4 以前のバージョンでは、独自の文字列データテーブルが保持されています。 これは、Windows 7 で実行されている.NET Framework 4.5 以降の.NET Frameworkのバージョンにも当てはまります。 Windows 8 以降のバージョンの Windows オペレーティング システムで実行されている.NET Framework 4.5 以降、ランタイムは文字列の比較と並べ替え操作をオペレーティング システムに委任します。 .NET Core および .NET 5 以降では、文字列の比較と並べ替えの情報は、Unicode ライブラリの International Components によって提供されます (Windows 10 May 2019 Updateより前のバージョンの Windows を除く)。 次の表に、.NET のバージョンと、文字の比較と並べ替えの基になっている Unicode 標準のバージョンを示します。

.NET バージョン Unicode 標準のバージョン
.NET Framework 1.1 Unicode 標準、バージョン 4.0.0
.NET Framework 2.0 Unicode 標準、バージョン 5.0.0
.NET Framework 3.5 Unicode 標準、バージョン 5.0.0
.NET Framework 4 Unicode 標準、バージョン 5.0.0
Windows 7 の .NET Framework 4.5 以降 Unicode 標準、バージョン 5.0.0
Windows 8 以降の Windows オペレーティング システムで 4.5 以降を.NET Frameworkする Unicode 標準、バージョン 6.3.0
.NET Core および .NET 5+ 基になるオペレーティング システムでサポートされている Unicode 標準のバージョンによって異なります。

文字列と埋め込み null 文字

.NET では、オブジェクトに String 埋め込み null 文字を含めることができます。これは、文字列の長さの一部としてカウントされます。 ただし、C や C++ などの一部の言語では、null 文字は文字列の末尾を示します。文字列の一部とは見なされず、文字列の長さの一部としてカウントされません。 つまり、C または C++ で記述された C および C++ のプログラマまたはライブラリが、オブジェクトに適用 String される場合、文字列に関して行う可能性がある次の一般的な前提は、必ずしも有効ではありません。

  • または wcslen 関数によってstrlen返される値は、必ずしも と等しいString.Lengthとは限りません。

  • 関数または wcscpy_s 関数によってstrcpy_s作成される文字列は、 メソッドによってString.Copy作成された文字列と必ずしも同一であるとは限りません。

オブジェクトをインスタンス化 String するネイティブの C および C++ コードと、プラットフォーム呼び出しを介してオブジェクトを渡される String コードは、埋め込まれた null 文字が文字列の末尾をマークすることを想定しないようにする必要があります。

文字列に埋め込まれた null 文字は、文字列が並べ替えられる (または比較される) 場合と、文字列が検索されるときにも異なる方法で処理されます。 インバリアント カルチャを使用した比較など、2 つの文字列間でカルチャに依存する比較を実行する場合、Null 文字は無視されます。 これらは、序数または大文字と小文字を区別しない序数比較でのみ考慮されます。 一方、、、、 などのContainsStartsWithIndexOfメソッドを使用して文字列を検索する場合、埋め込まれた null 文字は常に考慮されます。

文字列とインデックス

インデックスは、 内のオブジェクト ( Char Unicode 文字ではない) の位置です String。 インデックスは、文字列内の最初の位置 (インデックス位置 0) から始まる 0 から始まる負でない 0 から始まる数値です。 や LastIndexOfなどのIndexOf検索メソッドの数は、文字列インスタンス内の文字または部分文字列のインデックスを返します。

Chars[]プロパティを使用すると、文字列内のインデックス位置によって個々Charのオブジェクトにアクセスできます。 Chars[]プロパティは既定のプロパティ (Visual Basic の場合) またはインデクサー (C# および F# の場合) であるため、次のようなコードを使用して、文字列内の個々Charのオブジェクトにアクセスできます。 このコードでは、文字列内の空白文字または句読点文字を検索して、文字列に含まれる単語の数を確認します。

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.
string s1 = "This string consists of a single short sentence.";
int nWords = 0;

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

for i = 0 to s1.Length - 1 do
    if Char.IsPunctuation s1[i] || Char.IsWhiteSpace s1[i] then
        nWords <- nWords + 1
printfn $"The sentence\n   {s1}\nhas {nWords} words."
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
Module 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.

クラスは インターフェイスをStringIEnumerable実装するため、次の例に示すように、 コンストラクトを使用foreachして文字列内のオブジェクトを反復処理Charすることもできます。

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.
string s1 = "This string consists of a single short sentence.";
int nWords = 0;

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

for ch in s1 do
    if Char.IsPunctuation ch || Char.IsWhiteSpace ch then
        nWords <- nWords + 1
printfn $"The sentence\n   {s1}\nhas {nWords} words."
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
Module 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 文字は複数 Char のオブジェクトとしてエンコードされる可能性があるため、連続するインデックス値が連続する Unicode 文字に対応しない場合があります。 特に、文字列には、基本文字の後に 1 つ以上の組み合わせ文字またはサロゲート ペアによって形成される複数文字のテキスト単位を含めることができます。 オブジェクトではなく Char Unicode 文字を操作するには、 クラスと TextElementEnumerator クラス、または String.EnumerateRunes メソッドと 構造体をRune使用System.Globalization.StringInfoします。 次の例は、オブジェクトで動作するコードと Unicode 文字で Char 動作するコードの違いを示しています。 文の各単語の文字数またはテキスト要素の数を比較します。 文字列には、基本文字の後に結合文字が続く 2 つのシーケンスが含まれます。

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

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

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

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

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

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

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

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

Module 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

この例では、 メソッドと TextElementEnumerator クラスをStringInfo.GetTextElementEnumerator使用して文字列内のすべてのテキスト要素を列挙することで、テキスト要素を操作します。 また、 メソッドを呼び出すことで、各テキスト要素の開始インデックスを含む配列を StringInfo.ParseCombiningCharacters 取得することもできます。

個々 Char の値ではなくテキストの単位を操作する方法の詳細については、「 .NET での文字エンコードの概要」を参照してください。

null 文字列と空の文字列

宣言されているが、値が割り当てられていない文字列は です null。 その文字列でメソッドを呼び出そうとすると、 NullReferenceExceptionがスローされます。 null 文字列は、値が "" または String.Emptyである文字列である空の文字列とは異なります。 場合によっては、null 文字列または空の文字列をメソッド呼び出しの引数として渡すと、例外がスローされます。 たとえば、 メソッドに null 文字列を Int32.Parse 渡すと、 ArgumentNullExceptionがスローされ、空の文字列を渡すと が FormatExceptionスローされます。 それ以外の場合、メソッド引数には null 文字列または空の文字列を指定できます。 たとえば、クラスの実装を IFormattable 指定する場合は、null 文字列と空の文字列の両方を一般的な ("G") 書式指定子と同じにする必要があります。

Stringクラスには次の 2 つの便利なメソッドが含まれています。このメソッドを使用すると、文字列がnull空か空かをテストできます。

  • IsNullOrEmptyは、文字列 null が であるか、 と等しい String.Emptyかを示します。 このメソッドを使用すると、次のようなコードを使用する必要がなくなります。

    if (str == nullptr || str->Equals(String::Empty))
    
    if (str == null || str.Equals(String.Empty))
    
    if str = null || str.Equals String.Empty then
    
    If str Is Nothing OrElse str.Equals(String.Empty) Then
    
  • IsNullOrWhiteSpaceは、文字列が nullと等しい String.Emptyか、空白文字のみで構成されているかを示します。 このメソッドを使用すると、次のようなコードを使用する必要がなくなります。

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

次の例では、IsNullOrEmptyカスタム Temperature クラスのIFormattable.ToString実装で メソッドを使用します。 メソッドは、"G"、"C"、"F"、および "K" の書式指定文字列をサポートします。 空の書式指定文字列または値が null メソッドに渡される書式指定文字列の場合、その値は "G" 書式指定文字列に変更されます。

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));
   }                                   
}
member _.ToString(format: string, provider: IFormatProvider) =
    let format = 
        if String.IsNullOrEmpty format then "G" else format
    
    let provider: IFormatProvider = 
        if provider = null then CultureInfo.CurrentCulture else provider

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

不変性と StringBuilder クラス

Stringオブジェクトは、作成後に値を変更できないため、不変 (読み取り専用) と呼ばれます。 オブジェクトを変更するように見えるメソッドは、変更を String 含む新 String しいオブジェクトを実際に返します。

文字列は不変であるため、1 つの文字列と思われるものに対して繰り返し追加または削除を実行する文字列操作ルーチンでは、パフォーマンスが大幅に低下する可能性があります。 たとえば、次のコードでは、乱数ジェネレーターを使用して、0x052F 0x0001範囲内に 1000 文字の文字列を作成します。 コードは文字列連結を使用して という名前 strの既存の文字列に新しい文字を追加するように見えますが、実際には連結操作ごとに新しい String オブジェクトを作成します。

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 += (char)rnd.Next(1, 0x0530);
         if (str.Length % 60 == 0)
            str += Environment.NewLine;          
      }                    
      sw.Write(str);
      sw.Close();
   }
}
open System
open System.IO
open System.Text

do
    let rnd = Random()

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

Module 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

文字列の値に複数の変更をStringBuilderString加える操作には、 クラスの代わりに クラスを使用できます。 クラスの String インスタンスとは異なり、 StringBuilder オブジェクトは変更可能です。文字列から部分文字列を連結、追加、または削除すると、操作は 1 つの文字列に対して実行されます。 オブジェクトの値の StringBuilder 変更が完了したら、その StringBuilder.ToString メソッドを呼び出して文字列に変換できます。 次の例では、前の例で使用した を置き換えて String 、範囲内の 1,000 文字のランダムな文字を連結し、0x052Fを オブジェクトに0x0001 StringBuilder します。

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((char)rnd.Next(1, 0x0530));
         if (sb.Length % 60 == 0)
            sb.AppendLine();          
      }                    
      sw.Write(sb.ToString());
      sw.Close();
   }
}
open System
open System.IO
open System.Text

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

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

Module 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

序数とカルチャに依存する操作

クラスのメンバーは、 String オブジェクトに対して序数またはカルチャに依存する (言語的) 操作を String 実行します。 序数演算は、各 Char オブジェクトの数値に対して機能します。 カルチャに依存する操作は、オブジェクトの値に対して動作し、カルチャ固有の大文字と小文字の String 区別、並べ替え、書式設定、および解析ルールを考慮します。 カルチャに依存する操作は、明示的に宣言されたカルチャまたは暗黙的な現在のカルチャのコンテキストで実行されます。 2 種類の操作は、同じ文字列に対して実行されると、非常に異なる結果を生成できます。

.NET では、地域に依存しない英語のカルチャ設定に大まかに基づくインバリアント カルチャ (CultureInfo.InvariantCulture) を使用して、カルチャに依存しない言語文字列操作もサポートされています。 他 System.Globalization.CultureInfo の設定とは異なり、インバリアント カルチャの設定は、システムからシステム、および .NET のバージョン間で、1 台のコンピューターで一貫性を維持することが保証されます。 インバリアント カルチャは、すべてのカルチャで文字列比較と順序付けの安定性を確保するブラック ボックスの一種と見なすことができます。

重要

アプリケーションで、ファイル名や名前付きパイプなどのシンボリック識別子、または XML ファイル内のテキスト ベースのデータなどの永続化されたデータに関するセキュリティ上の決定を行う場合、操作ではカルチャに依存する比較の代わりに序数比較を使用する必要があります。 これは、カルチャに依存する比較では、有効なカルチャに応じて異なる結果が得られるのに対し、序数比較は比較される文字のバイナリ値のみに依存するためです。

重要

文字列操作を実行するほとんどのメソッドには、 型 StringComparisonのパラメーターを持つオーバーロードが含まれています。これにより、メソッドが序数またはカルチャに依存する操作を実行するかどうかを指定できます。 一般に、このオーバーロードを呼び出して、メソッド呼び出しの意図を明確にする必要があります。 文字列に対して序数操作とカルチャ依存操作を使用するためのベスト プラクティスとガイダンスについては、「 文字列を使用するためのベスト プラクティス」を参照してください。

大文字と 小文字の区別解析と書式設定比較と並べ替えおよび等価性のテストの 操作は、序数またはカルチャに依存します。 次のセクションでは、操作の各カテゴリについて説明します。

ヒント

メソッド呼び出しの意図を明確にするメソッド オーバーロードを常に呼び出す必要があります。 たとえば、 メソッドをCompare(String, String)呼び出して、現在のカルチャの規則を使用して 2 つの文字列のカルチャに依存する比較を実行する代わりに、 引数のStringComparison.CurrentCulture値をCompare(String, String, StringComparison)指定して メソッドをcomparisonType呼び出す必要があります。 詳細については、「文字列を使用するためのベスト プラクティス」を参照してください。

並べ替えと比較の操作で使用される文字の太さに関する情報を含む一連のテキスト ファイルである並べ替えの重みテーブルは、次のリンクからダウンロードできます。

大文字小文字の区別

大文字と小文字の規則は、Unicode 文字の大文字と小文字を変更する方法を決定します。たとえば、小文字から大文字までです。 多くの場合、大文字と小文字の区別操作は文字列比較の前に実行されます。 たとえば、別の大文字の文字列と比較できるように、文字列を大文字に変換できます。 または メソッドを呼び出すことで文字列内の文字を小文字に変換でき、 メソッドまたは ToLowerInvariantToUpperInvariant メソッドを呼ToLowerび出ToUpperすことで大文字に変換できます。 さらに、 メソッドを TextInfo.ToTitleCase 使用して、文字列をタイトル ケースに変換することもできます。

注意

Linux および macOS システムでのみ実行されている .NET Core: C カルチャと Posix カルチャの照合順序の動作では、予期される Unicode 照合順序が使用されないため、常に大文字と小文字が区別されます。 カルチャに依存する、大文字と小文字を区別しない並べ替え操作を実行する場合は、C または Posix 以外のカルチャを使うことをお勧めします。

大文字と小文字の操作は、現在のカルチャ、指定したカルチャ、または不変カルチャのルールに基づいて行うことができます。 ケース マッピングは使用するカルチャによって異なる場合があるため、大文字と小文字の区別操作の結果はカルチャによって異なる場合があります。 大文字と小文字の実際の違いは、次の 3 種類です。

  • 大文字 I (U+0049)、英小文字 I (U+0069)、上のドット付きラテン大文字 I (U+0130)、およびラテン小文字のドットレス I (U+0131) のケース マッピングの違い。 tr-TR (トルコ語 (トルコ)) と az-Latn-AZ (アゼルバイジャン、ラテン) カルチャ、および tr、az、az-Latn ニュートラル カルチャでは、ラテン大文字 I の小文字の等価はラテン小文字 DOTLESS I で、大文字の小文字 I はラテン小文字 I に相当し、大文字の小文字 I は DOT ABOVE のラテン大文字 I です。 インバリアント カルチャを含む他のすべてのカルチャでは、LATIN SMALL LETTER I と LATIN CAPITAL LETTER I は小文字と大文字に相当します。

    次の例は、カルチャに依存する大文字と小文字の比較に依存している場合に、ファイル システムアクセスを防ぐために設計された文字列比較が失敗する方法を示しています。 (インバリアント カルチャの大文字と小文字の表記規則を使用する必要があります)。

    using System;
    using System.Globalization;
    using System.Threading;
    
    public class Example
    {
       const string disallowed = "file";
       
       public static void Main()
       {
          IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt");
       }
    
       private static void IsAccessAllowed(String resource)
       {
          CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
                                     CultureInfo.CreateSpecificCulture("tr-TR") };
          String scheme = null;
          int index = resource.IndexOfAny( new Char[] { '\\', '/' } );
          if (index > 0) 
             scheme = resource.Substring(0, index - 1);
    
          // Change the current culture and perform the comparison.
          foreach (var culture in cultures) {
             Thread.CurrentThread.CurrentCulture = culture;
             Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
             Console.WriteLine(resource);
             Console.WriteLine("Access allowed: {0}", 
                               ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase));      
             Console.WriteLine();
          }   
       }
    }
    // The example displays the following output:
    //       Culture: English (United States)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: False
    //       
    //       Culture: Turkish (Turkey)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: True
    
    open System
    open System.Globalization
    open System.Threading
    
    let disallowed = "file"
    
    let isAccessAllowed (resource: string) =
        let cultures = 
            [| CultureInfo.CreateSpecificCulture "en-US"
               CultureInfo.CreateSpecificCulture "tr-TR" |]
        let index = resource.IndexOfAny [| '\\'; '/' |]
        let scheme =
            if index > 0 then
                resource.Substring(0, index - 1)
            else 
                null
    
        // Change the current culture and perform the comparison.
        for culture in cultures do
            Thread.CurrentThread.CurrentCulture <- culture
            printfn $"Culture: {CultureInfo.CurrentCulture.DisplayName}"
            printfn $"{resource}"
            printfn $"Access allowed: {String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase) |> not}"
            printfn ""
            
    isAccessAllowed @"FILE:\\\c:\users\user001\documents\FinancialInfo.txt"
    // The example displays the following output:
    //       Culture: English (United States)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: False
    //
    //       Culture: Turkish (Turkey)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: True
    
    Imports System.Globalization
    Imports System.Threading
    
    Module 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
    
  • インバリアント カルチャと他のすべてのカルチャ間のケース マッピングの違い。 このような場合、インバリアント カルチャの大文字と小文字の規則を使用して文字を大文字または小文字に変更すると、同じ文字が返されます。 他のすべてのカルチャでは、別の文字が返されます。 影響を受ける文字の一部を次の表に示します。

    文字 に変更された場合 戻り値
    ミクロン記号 (U+00B5) 大文字 ギリシャ大文字 MU (U+-39C)
    上にドットがある英大文字 I (U+0130) 小文字 英小文字 I (U+0069)
    英小文字ドットレス I (U+0131) 大文字 英大文字 I (U+0049)
    英小文字 LONG S (U+017F) 大文字 英大文字 S (U+0053)
    英大文字 D と小文字 Z と CARON (U+01C5) 小文字 英小文字 DZ と CARON (U+01C6)
    ギリシャ語の YPOGEGRAMMENI の組み合わせ (U+0345) 大文字 ギリシャ大文字 IOTA (U+0399)
  • ASCII 文字範囲内の 2 文字の大文字と小文字が混在するペアのケース マッピングの違い。 ほとんどのカルチャでは、2 文字の大文字と小文字のペアは、同等の 2 文字の大文字または小文字のペアと等しくなります。 これは、次のカルチャの次の 2 文字のペアでは当てはまらないのは、それぞれのケースでディグラフと比較されるためです。

    • hr-HR (クロアチア語 (クロアチア)) 文化の "lJ" と "nJ"。

    • cs-CZ (チェコ共和国) と sk-SK (スロバキア (スロバキア)) カルチャの "cH"。

    • da-DK (デンマーク) 文化の "aA"。

    • hu-HU (ハンガリー)) カルチャの "cS"、"dZ"、"dZS"、"nY"、"sZ"、"tY"、および "zS"。

    • es-ES_tradnl (スペイン語 (スペイン語、伝統的な並べ替え)) カルチャの "cH" と "lL"。

    • vi-VN (ベトナム (ベトナム)) カルチャの "cH"、"gI"、"kH"、"nG" "nH"、"pH"、"qU"、"tH"、および "tR" 。

    ただし、固定文字列または識別子ではこれらのペアが一般的でないため、これらのペアのカルチャに依存した比較によって問題が発生する状況は通常とは異なります。

次の例は、文字列を大文字に変換するときのカルチャ間の大文字と小文字の区別規則の違いをいくつか示しています。

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
open System
open System.Globalization
open System.IO

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

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

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

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

Module 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

解析と書式設定

書式設定と解析は逆操作です。 書式設定ルールは、日付と時刻や数値などの値を文字列形式に変換する方法を決定します。一方、解析ルールでは、文字列表現を日付と時刻などの値に変換する方法が決まります。 書式設定と解析ルールはどちらもカルチャ規則に依存します。 次の例は、カルチャ固有の日付文字列を解釈するときに発生する可能性があるあいまいさを示しています。 日付文字列の生成に使用されたカルチャの規則を知らなければ、2011 年 3 月 1 日、2011 年 3 月 1 日、2011 年 1 月 3 日または 2011 年 3 月 1 日を表すかどうかを把握することはできません。

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

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

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

Module 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

同様に、次の例に示すように、1 つの文字列は、解析操作で使用される規則を持つカルチャに応じて異なる日付を生成できます。

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

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

Module 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

文字列の比較と並べ替え

文字列の比較と並べ替えの規則は、カルチャによって異なります。 たとえば、並べ替え順序は、ふりがなや文字の視覚的表現に基づく場合があります。 東アジア圏の言語では、文字が表意文字の画数と部首によって並べ替えられます。 また、並べ替えは、言語やカルチャで使用されているアルファベットの順序によっても異なります。 たとえば、デンマーク語の文字 "Æ" は、アルファベットでは "Z" の後に位置します。 さらに、比較では大文字と小文字が区別されたり、大文字と小文字が区別されたり、カルチャによって大文字と小文字が区別されたりする場合があります。 一方、序数比較では、文字列の比較と並べ替え時に、文字列内の個々の文字の Unicode コード ポイントが使用されます。

並べ替えルールは、Unicode 文字のアルファベット順と、2 つの文字列が相互にどのように比較されるかを決定します。 たとえば、 メソッドは パラメーターに String.Compare(String, String, StringComparison) 基づいて 2 つの文字列を StringComparison 比較します。 パラメーター値が の場合、メソッドは StringComparison.CurrentCulture現在のカルチャの規則を使用する言語比較を実行します。パラメーター値が の場合、メソッドは StringComparison.Ordinal序数比較を実行します。 したがって、次の例に示すように、現在のカルチャが米国英語の場合、メソッドの String.Compare(String, String, StringComparison) 最初の呼び出し (カルチャに依存する比較を使用) では "a" が "A" 未満と見なされますが、同じメソッドの 2 番目の呼び出し (序数比較を使用) では "a" が "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
open System
open System.Globalization
open System.Threading

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

Module 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 では、単語、文字列、および序数の並べ替え規則がサポートされています。

  • 単語での並べ替えでは、英数字以外の特定の Unicode 文字には特別な重みが割り当てられる、カルチャに依存した文字列の比較が行われます。 たとえば、ハイフン (-) には非常に小さな重みが割り当てられ、並べ替えられたリスト内で "coop" と "co-op" が隣り合って表示される場合があります。 単語の並べ替えルールを String 使用して 2 つの文字列を比較するメソッドの一覧については、「 カテゴリ別の文字列操作 」セクションを参照してください。

  • 文字列の並べ替えでは、カルチャに依存する比較も実行されます。 これは単語の並べ替えに似ていますが、特殊なケースがなく、英数字以外のすべての記号がすべての英数字 Unicode 文字の前に来る点が除きます。 値 が指定されたパラメーターを持つメソッド オーバーロードを CompareInfo.Compare 呼び出すことで、文字列並べ替え規則を options 使用して 2 つの文字列を CompareOptions.StringSort比較できます。 これは、文字列並べ替え規則を使用して 2 つの文字列を比較するために .NET が提供する唯一のメソッドであることに注意してください。

  • 序数の並べ替えでは、文字列内の各 Char オブジェクトの数値に基づいて文字列を比較します。 文字の小文字と大文字のバージョンのコード ポイントが異なるため、序数比較では自動的に大文字と小文字が区別されます。 ただし、case が重要でない場合は、大文字と小文字を無視する序数比較を指定できます。 これは、インバリアント カルチャを使用して文字列を大文字に変換し、結果に対して序数比較を実行することと同じです。 序数の並べ替え規則を String 使用して 2 つの文字列を比較するメソッドの一覧については、「 カテゴリ別の文字列操作 」セクションを参照してください。

カルチャに依存する比較とは、 プロパティでCultureInfo.InvariantCulture指定されたインバリアント カルチャを含め、オブジェクトをCultureInfo明示的または暗黙的に使用する比較です。 暗黙的なカルチャは、プロパティと CultureInfo.CurrentCulture プロパティで指定される現在のThread.CurrentCultureカルチャです。 カルチャ間では、アルファベット文字 (つまり、プロパティが返すtrue文字Char.IsLetter) の並べ替え順序に大きいバリエーションがあります。 などのCompare(String, String, CultureInfo, CompareOptions)文字列比較メソッドにオブジェクトを指定することで、特定のカルチャの規則をCultureInfo使用するカルチャに依存する比較を指定できます。 メソッドの適切なオーバーロードに または 以外CompareOptions.OrdinalIgnoreCaseCompareOptions.Ordinalの列挙体のメンバーを指定することで、現在のカルチャのCompareOptions規則をStringComparison.CurrentCultureStringComparison.CurrentCultureIgnoreCase使用するカルチャ依存の比較をCompare指定できます。 通常、カルチャに依存する比較は並べ替えに適しているのに対し、序数比較は適切ではありません。 通常、序数比較は、2 つの文字列が等しいかどうかを判断するのに適しています (つまり、ID を判断する場合) 一方、カルチャに依存する比較は適していません。

次の例は、カルチャに依存する比較と序数比較の違いを示しています。 この例では、序数比較と da-DK カルチャと en-US カルチャの規則を使用して、"Apple"、"Æble"、および "AEble" の 3 つの文字列を評価します (各カルチャは、メソッドが呼び出された時点 Compare の既定のカルチャです)。 デンマーク語は文字 "Æ" を個々の文字として扱い、アルファベットの "Z" の後に並べ替えるので、文字列 "Æble" は "Apple" より大きくなります。 ただし、"Æble" は "AEble" と同等とは見なされないため、"Æble" も "AEble" よりも大きくなります。 en-US カルチャには文字 "Æ" は含まれていませんが、"Æble" が "Apple" より小さいが "AEble" と等しい理由を説明する "AE" と同等として扱われます。 一方、序数比較では、"Apple" は "Æble" より小さく、"Æble" は "AEble" より大きいと見なされます。

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

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

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

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

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

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

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

適切な並べ替え方法または文字列比較方法を選択するには、次の一般的なガイドラインを使用します。

  • 文字列をユーザーのカルチャに基づいて並べ替える場合は、現在のカルチャの規則に基づいて順序付けする必要があります。 ユーザーのカルチャが変更された場合、並べ替えられた文字列の順序も適宜変更されます。 たとえば、類義語辞典アプリケーションでは、常にユーザーのカルチャに基づいて単語を並べ替える必要があります。

  • 特定のカルチャの規則に基づいて文字列を並べ替える場合は、そのカルチャを表すオブジェクトを CultureInfo 比較メソッドに指定して順序付けする必要があります。 たとえば、学生に特定の言語を教えるために設計されたアプリケーションでは、その言語を話すカルチャの 1 つの規則に基づいて文字列を並べ替える必要があります。

  • カルチャ間で文字列の順序を変更しない場合は、インバリアント カルチャの規則に基づいて文字列を並べ替えるか、序数比較を使用する必要があります。 たとえば、序数並べ替えを使用して、ファイル、プロセス、ミューテックス、または名前付きパイプの名前を整理します。

  • セキュリティ上の決定を伴う比較 (ユーザー名が有効かどうかなど) については、 メソッドのオーバーロードを呼び出して、常に等価性の序数テストを実行する Equals 必要があります。

注意

文字列比較で使用されるカルチャに依存する並べ替えと大文字と小文字の区別の規則は、.NET のバージョンによって異なります。 .NET Core では、文字列比較は、基になるオペレーティング システムでサポートされている Unicode 標準のバージョンによって異なります。 Windows 8 以降で実行されている.NET Framework 4.5 以降のバージョンでは、並べ替え、大文字と小文字の区別、正規化、および Unicode 文字情報は Unicode 6.0 標準に準拠しています。 他の Windows オペレーティング システムでは、Unicode 5.0 標準に準拠しています。

単語、文字列、および序数の並べ替え規則の詳細については、トピックを System.Globalization.CompareOptions 参照してください。 各ルールを使用するタイミングに関するその他の推奨事項については、「 文字列を使用するためのベスト プラクティス」を参照してください。

通常、文字列の並べ替え順序を決定するために、 などの Compare 文字列比較メソッドを直接呼び出す必要はありません。 代わりに、 や List<T>.SortなどのArray.Sortメソッドを並べ替えることで比較メソッドが呼び出されます。 次の例では、文字列比較メソッドを明示的に呼び出さずに、4 つの異なる並べ替え操作 (現在のカルチャを使用した単語の並べ替え、インバリアント カルチャを使用した単語の並べ替え、序数の並べ替え、インバリアント カルチャを使用した文字列の並べ替え) を実行します。ただし、使用する比較の種類は指定します。 並べ替えの種類ごとに、配列内の文字列の一意の順序が生成されることに注意してください。

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
open System
open System.Collections.Generic
open System.Globalization

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

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

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

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

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

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

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

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

Module 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 は並べ替えキーを使用して、文化的に機密性の高い文字列比較をサポートします。 文字列内の各文字には、アルファベット順、大文字と小文字の区別、発音の区別など、さまざまなカテゴリの並べ替えウェイトが指定されます。 クラスによって SortKey 表される並べ替えキーは、特定の文字列に対してこれらの重みのリポジトリを提供します。 アプリが同じ文字列セットに対して多数の検索操作または並べ替え操作を実行する場合は、使用するすべての文字列の並べ替えキーを生成して格納することで、パフォーマンスを向上させることができます。 並べ替え操作または比較操作が必要な場合は、文字列の代わりに並べ替えキーを使用します。 詳細については、SortKey クラスを参照してください。

文字列比較規則を指定しない場合、 などの Array.Sort(Array) 並べ替えメソッドは、カルチャに依存する大文字と小文字を区別する並べ替えを文字列に対して実行します。 次の例は、現在のカルチャを変更すると、配列内の並べ替えられた文字列の順序にどのように影響するかを示しています。 3 つの文字列の配列を作成します。 最初に、System.Threading.Thread.CurrentThread.CurrentCulture プロパティを en-US に設定し、Array.Sort(Array) メソッドを呼び出します。 これよって、英語 (米国) カルチャの並べ替え規則に基づく並べ替え順序が適用されます。 次に、System.Threading.Thread.CurrentThread.CurrentCulture プロパティを da-DK に設定し、再度 Array.Sort メソッドを呼び出します。 適用される並べ替え順序が en-US の並べ替え順序と異なる点に注意してください。これは、デンマーク語 (デンマーク) の並べ替え規則が使用されるためです。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

警告

文字列を比較する主な目的が、文字列が等しいかどうかを判断する場合は、 メソッドを呼び出す String.Equals 必要があります。 通常は、 を使用 Equals して序数比較を実行する必要があります。 メソッドは String.Compare 、主に文字列を並べ替えることを目的としています。

String.IndexOfなどのString.StartsWith文字列検索メソッドは、カルチャ依存または序数の文字列比較を実行することもできます。 次の例は、 メソッドを使用した序数とカルチャに依存する比較の違いを IndexOf 示しています。 現在のカルチャが英語 (米国) であるカルチャに依存する検索では、サブ文字列 "oe" が合字 "œ" と一致すると見なされます。 ソフト ハイフン (U+00AD) は幅 0 の文字であるため、検索ではソフト ハイフンが と等価 Empty として扱われ、文字列の先頭で一致が検索されます。 一方、序数検索では、どちらの場合も一致が見つかりません。

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

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

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

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

// The example displays the following output:
//       'oe' found in œufs at position 0
//       'oe' not found in œufs
//       'œu' found in oeufs at position 0
//       'œu' not found in oeufs
//
//       '­' found in co­operative at position 0
//       '­' found in co­operative at position 2
Module 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

文字列で検索する

String.IndexOfなどのString.StartsWith文字列検索メソッドでは、カルチャに依存する文字列または序数の文字列比較を実行して、指定した文字列に文字または部分文字列があるかどうかを判断することもできます。

メソッドなどのIndexOf個々の文字を検索するクラス内Stringの検索メソッド、または メソッドなどのIndexOfAny文字セットの 1 つはすべて、序数検索を実行します。 カルチャに依存する文字の検索を実行するには、 や CompareInfo.LastIndexOf(String, Char)などのCompareInfo.IndexOf(String, Char)メソッドをCompareInfo呼び出す必要があります。 序数とカルチャに依存する比較を使用して文字を検索した結果は大きく異なる場合があることに注意してください。 たとえば、合字 "Æ" (U+00C6) などの事前計算済みの Unicode 文字の検索は、カルチャに応じて、"AE" (U+041U+0045) などの正しいシーケンス内のコンポーネントの出現と一致する場合があります。 次の例は、個々の文字を検索するときの メソッドと CompareInfo.IndexOf(String, Char) メソッドの違いString.IndexOf(Char)を示しています。 合字 "æ" (U+00E6) は、en-US カルチャの規則を使用する場合は文字列 "aerial" にありますが、da-DK カルチャの規則を使用する場合や序数比較を実行する場合は見つかりません。

using System;
using System.Globalization;

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

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

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

Module 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

一方、 StringStringComparisonのパラメーターで検索オプションが明示的に指定されていない場合、文字ではなく文字列を検索するクラス メソッドはカルチャに依存する検索を実行します。 唯一の例外は です Contains。これは序数検索を実行します。

等価性のテスト

メソッドを String.Compare 使用して、並べ替え順序で 2 つの文字列のリレーションシップを確認します。 通常、これはカルチャに依存する操作です。 これに対し、 メソッドを String.Equals 呼び出して等価性をテストします。 通常、等価性のテストでは、ユーザー入力と、有効なユーザー名、パスワード、ファイル システム パスなどの既知の文字列が比較されるため、通常は序数演算です。

警告

メソッドを呼び出し、戻り値が String.Compare 0 かどうかを判断することで、等価性をテストできます。 ただし、この方法は推奨されません。 2 つの文字列が等しいかどうかを判断するには、 メソッドのいずれかのオーバーロード String.Equals を呼び出す必要があります。 どちらのメソッドにも比較の種類を明示的に指定するパラメーターが含System.StringComparisonまれているため、呼び出すオーバーロードはインスタンス Equals(String, StringComparison) メソッドまたは静的Equals(String, String, StringComparison)メソッドのいずれかです。

次の例は、序数を代わりに使用する必要がある場合に、カルチャに依存する比較を実行して等しいかどうかを示しています。 この場合、コードの目的は、URL の先頭と文字列 "FILE://" の大文字と小文字を区別しない比較を実行することで、"FILE://" または "file://" で始まる URL からのファイル システム アクセスを禁止することです。 ただし、"file://" で始まる URL でトルコ語 (トルコ) カルチャを使用してカルチャに依存する比較を実行すると、トルコの大文字の小文字 "i" が "I" ではなく "İ" であるため、等価性の比較は失敗します。 その結果、ファイル システムへのアクセスが誤って許可されます。 一方、序数比較を実行すると、等価性の比較は成功し、ファイル システムへのアクセスは拒否されます。

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

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

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

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

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

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

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

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

正規化

一部の Unicode 文字には、複数の表現があります。 たとえば、次のいずれかのコード ポイントは、文字 "ắ" を表すことができます。

  • U+1EAF

  • U+0103 U+0301

  • U+0061 U+0306 U+0301

1 つの文字に対して複数の表現を使用すると、検索、並べ替え、照合、およびその他の文字列操作が複雑になります。

Unicode 標準では、同等のバイナリ表現のいずれかに対して Unicode 文字の 1 つのバイナリ表現を返す正規化と呼ばれるプロセスを定義します。 正規化では、さまざまなルールに従う正規化フォームと呼ばれるいくつかのアルゴリズムを使用できます。 .NET では、Unicode 正規化形式 C、D、KC、KD がサポートされています。 文字列が同じ正規化形式に正規化されている場合は、序数比較を使用して比較できます。

序数比較は、各文字列内の対応する Char オブジェクトの Unicode スカラー値のバイナリ比較です。 Stringクラスには、次のような序数比較を実行できるメソッドが多数含まれています。

メソッドを呼び出して、文字列が正規化形式 C に正規化されているかどうかを判断するか、 メソッドをString.IsNormalized(NormalizationForm)呼び出String.IsNormalized()して、文字列が指定された正規化フォームに正規化されているかどうかを判断できます。 メソッドを String.Normalize() 呼び出して文字列を正規化形式 C に変換することも、 メソッドを String.Normalize(NormalizationForm) 呼び出して文字列を指定した正規化形式に変換することもできます。 文字列の正規化と比較の詳細については、 メソッドと Normalize(NormalizationForm) メソッドに関するページをNormalize()参照してください。

次の簡単な例は、文字列の正規化を示しています。 3 つの異なる文字列で文字 "ố" を 3 つの異なる方法で定義し、等しい場合に序数比較を使用して、各文字列が他の 2 つの文字列と異なることを判断します。 次に、各文字列をサポートされている正規化形式に変換し、指定された正規化形式で各文字列の序数比較を再度実行します。 いずれの場合も、2 番目の等値テストでは、文字列が等しいことを示します。

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

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

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

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

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

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

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

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

Module 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

正規化フォームと正規化フォームの詳細については、unicode.org Web サイトの「Unicode 標準付録 #15: Unicode 正規化フォーム」および「正規化に関する FAQ」を参照してくださいSystem.Text.NormalizationForm

カテゴリ別の文字列操作

クラスは String 、文字列の比較、文字列の等価性のテスト、文字列内の文字または部分文字列の検索、文字列の変更、文字列からの部分文字列の抽出、文字列の結合、値の書式設定、文字列のコピー、および文字列の正規化を行うメンバーを提供します。

文字列を比較する

String のメソッドを使用して、並べ替え順序で文字列を比較して相対位置を決定できます。

  • Compare は、並べ替え順序で 1 つの文字列と 2 番目の文字列の関係を示す整数を返します。

  • CompareOrdinal は、コード ポイントの比較に基づいて、1 つの文字列と 2 番目の文字列の関係を示す整数を返します。

  • CompareTo は、現在の文字列インスタンスと 2 番目の文字列の並べ替え順序の関係を示す整数を返します。 メソッドは CompareTo(String) 、 クラスの IComparable および IComparable<T> 実装を String 提供します。

文字列の等価性をテストする

メソッドを Equals 呼び出して、2 つの文字列が等しいかどうかを判断します。 インスタンス Equals(String, String, StringComparison) と静的 Equals(String, StringComparison) オーバーロードを使用すると、比較がカルチャに依存するか序数であるか、大文字と小文字を区別するか無視するかを指定できます。 等価性のほとんどのテストは序数であり、システム リソース (ファイル システム オブジェクトなど) へのアクセスを決定する等価性の比較は常に序数である必要があります。

文字列内の文字を検索する

クラスには String 、次の 2 種類の検索メソッドが含まれています。

  • 特定の部分文字列が文字列インスタンスに存在するかどうかを示す値を返す Boolean メソッド。 これには、ContainsEndsWithおよび StartsWith メソッドが含まれます。

  • 文字列インスタンス内の部分文字列の開始位置を示すメソッド。 これには、IndexOfIndexOfAnyLastIndexOf、および LastIndexOfAny の各メソッドが含まれます。

警告

文字列で特定の部分文字列ではなく特定のパターンを検索する場合は、正規表現を使用する必要があります。 詳細については、「 .NET 正規表現」を参照してください。

文字列を変更する

Stringクラスには、文字列の値を変更するために表示される次のメソッドが含まれています。

  • Insert は、現在 String のインスタンスに文字列を挿入します。

  • PadLeft は、文字列の先頭に指定した文字の 1 つ以上の出現箇所を挿入します。

  • PadRight は、文字列の末尾に指定された文字の 1 つ以上の出現箇所を挿入します。

  • Remove は、現在 String のインスタンスから部分文字列を削除します。

  • Replace は、部分文字列を現在 String のインスタンス内の別の部分文字列に置き換えます。

  • ToLower 文字列 ToLowerInvariant 内のすべての文字を小文字に変換します。

  • ToUpper 文字列 ToUpperInvariant 内のすべての文字を大文字に変換します。

  • Trim は、文字列の先頭と末尾から文字のすべての出現箇所を削除します。

  • TrimEnd は、文字列の末尾から文字のすべての出現箇所を削除します。

  • TrimStart は、文字列の先頭から文字のすべての出現箇所を削除します。

重要

すべての文字列変更メソッドは、新しい String オブジェクトを返します。 現在のインスタンスの値は変更されません。

文字列から部分文字列を抽出する

メソッドは String.Split 、1 つの文字列を複数の文字列に分割します。 メソッドのオーバーロードを使用すると、複数の区切り記号を指定して、メソッドが抽出する部分文字列の数を制限したり、部分文字列から空白をトリミングしたり、空の文字列 (区切り記号が隣接する場合に発生する) を返される文字列に含めるかどうかを指定したりできます。

文字列を結合する

文字列連結には、次 String のメソッドを使用できます。

  • Concat は、1 つ以上の部分文字列を 1 つの文字列に結合します。

  • Join は、1 つ以上の部分文字列を 1 つの要素に連結し、各部分文字列の間に区切り記号を追加します。

値の書式設定

メソッドは String.Format 、複合書式設定機能を使用して、文字列内の 1 つ以上のプレースホルダーを、あるオブジェクトまたは値の文字列表現に置き換えます。 メソッドは Format 、多くの場合、次のことを行うために使用されます。

  • 数値の文字列表現を文字列に埋め込む。

  • 日付と時刻の値の文字列表現を文字列に埋め込む。

  • 列挙値の文字列表現を文字列に埋め込む。

  • インターフェイスをサポートするオブジェクトの文字列表現を IFormattable 文字列に埋め込む場合。

  • 大きな文字列内のフィールド内の部分文字列を右揃えまたは左揃えする。

書式設定操作と例の詳細については、オーバーロードの概要に関するページを Format 参照してください。

文字列をコピーします。

String のメソッドを呼び出して、文字列のコピーを作成できます。

  • Clone は、既存 String の オブジェクトへの参照を返します。

  • Copy は、既存の文字列のコピーを作成します。

  • CopyTo は、文字列の一部を文字配列にコピーします。

文字列を正規化する

Unicode では、1 つの文字に複数のコード ポイントを含めることができます。 正規化では、これらの同等の文字が同じバイナリ表現に変換されます。 メソッドは String.Normalize 正規化を実行し String.IsNormalized 、メソッドは文字列が正規化されているかどうかを判断します。

詳細と例については、このトピックの前半の 正規化 に関するセクションを参照してください。

コンストラクター

String(Char*)

String クラスの新しいインスタンスを初期化し、指定した Unicode 文字配列を指すポインターにより示される値に設定します。

String(Char*, Int32, Int32)

String クラスの新しいインスタンスを初期化し、Unicode 文字の配列を指す指定のポインター、配列内の開始文字位置、および長さにより示される値に設定します。

String(Char, Int32)

String クラスの新しいインスタンスを初期化し、指定した回数だけ繰り返した指定の Unicode 文字が示す値に設定します。

String(Char[])

String クラスの新しいインスタンスを、指定した文字配列で示された Unicode 文字に初期化します。

String(Char[], Int32, Int32)

String クラスの新しいインスタンスを初期化し、Unicode 文字の配列、配列内の開始文字位置、および長さにより示される値に設定します。

String(ReadOnlySpan<Char>)

String クラスの新しいインスタンスを、指定した読み取り専用スパンで示された Unicode 文字に初期化します。

String(SByte*)

String クラスの新しいインスタンスを初期化し、8 ビット符号付き整数の配列を指すポインターにより示される値に設定します。

String(SByte*, Int32, Int32)

String クラスの新しいインスタンスを初期化し、8 ビット符号付き整数の配列を指す指定のポインター、配列内の開始位置、および長さにより示される値に設定します。

String(SByte*, Int32, Int32, Encoding)

String クラスの新しいインスタンスを初期化し、8 ビット符号付き整数の配列を指す指定のポインター、配列内の開始位置、長さ、および Encoding オブジェクトにより示される値に設定します。

フィールド

Empty

空の文字列を表します。 このフィールドは読み取り専用です。

プロパティ

Chars[Int32]

現在の String オブジェクト内の指定された位置にある Char オブジェクトを取得します。

Length

現在の String オブジェクト内の文字数を取得します。

メソッド

Clone()

この Stringインスタンスへの参照を返します。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、それらの相対位置を並べ替え順序で示す整数を返します。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを設定できます。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを指定し、比較に影響を及ぼすカルチャ固有の情報を使用します。

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

指定した 2 つの String オブジェクトの部分文字列を比較し、2 つの部分文字列の互いのリレーションシップを並べ替え順序で示す整数を返します。比較時に、指定した比較オプションと、比較に影響を及ぼすカルチャ固有の情報を使用します。

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

指定した規則を使用して、指定した 2 つの String オブジェクトの部分文字列を比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。

Compare(String, String)

指定した 2 つの String オブジェクトを比較し、それらの相対位置を並べ替え順序で示す整数を返します。

Compare(String, String, Boolean)

指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを設定できます。

Compare(String, String, Boolean, CultureInfo)

指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。比較時に、大文字と小文字を区別するかどうかを指定し、比較に影響を及ぼすカルチャ固有の情報を使用します。

Compare(String, String, CultureInfo, CompareOptions)

指定した 2 つの String オブジェクトを比較し、2 つの文字列の互いのリレーションシップを並べ替え順序で示す整数を返します。比較時に、指定した比較オプションと、比較に影響を及ぼすカルチャ固有の情報を使用します。

Compare(String, String, StringComparison)

指定した規則を使用して、指定した 2 つの String オブジェクトを比較し、並べ替え順序におけるそれらの相対位置を示す整数を返します。

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

それぞれの部分文字列の対応する Char オブジェクトの数値を評価することにより、指定した 2 つの String オブジェクトの部分文字列を比較します。

CompareOrdinal(String, String)

それぞれの文字列の対応する String オブジェクトの数値を評価することで、指定した 2 つの Char を比較します。

CompareTo(Object)

このインスタンスと指定した Object とを比較し、並べ替え順序において、このインスタンスの位置が指定した Object の前、後ろ、または同じのいずれであるかを示します。

CompareTo(String)

このインスタンスと指定した String オブジェクトとを比較し、並べ替え順序において、このインスタンスの位置が指定した文字列の前、後ろ、または同じのいずれであるかを示します。

Concat(IEnumerable<String>)

IEnumerable<T> 型の構築された String コレクションのメンバーを連結します。

Concat(Object)

指定したオブジェクトの文字列表現を作成します。

Concat(Object, Object)

指定した 2 つのオブジェクトの文字列形式を連結します。

Concat(Object, Object, Object)

指定した 3 つのオブジェクトの文字列形式を連結します。

Concat(Object, Object, Object, Object)

4 つの指定したオブジェクトと、オプションの可変長パラメーター リストで指定した任意のオブジェクトの文字列表現を連結します。

Concat(Object[])

指定された Object 配列の要素の文字列表記を連結します。

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

2 つの指定された読み取り専用文字スパンの文字列形式を連結します。

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

3 つの指定された読み取り専用文字スパンの文字列形式を連結します。

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

4 つの指定された読み取り専用文字スパンの文字列形式を連結します。

Concat(String, String)

指定した 2 つの String インスタンスを連結します。

Concat(String, String, String)

String の指定した 3 つのインスタンスを連結します。

Concat(String, String, String, String)

指定した 4 つの String インスタンスを連結します。

Concat(String[])

指定した String 配列の要素を連結します。

Concat<T>(IEnumerable<T>)

IEnumerable<T> 実装のメンバーを連結します。

Contains(Char)

指定した文字がこの文字列内に存在するかどうかを示す値を返します。

Contains(Char, StringComparison)

指定された比較規則を使用して、指定された文字がこの文字列内に含まれるかどうかを示す値を返します。

Contains(String)

指定した部分文字列がこの文字列内に存在するかどうかを示す値を返します。

Contains(String, StringComparison)

指定された比較規則を使用して、指定された文字列がこの文字列内に含まれるかどうかを示す値を返します。

Copy(String)
互換性のために残されています。

指定した String と同じ値を使用して、String の新しいインスタンスを作成します。

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

このインスタンスの指定位置から指定した数の文字を、Unicode 文字の配列内の指定位置へコピーします。

CopyTo(Span<Char>)

この文字列の内容をコピー先スパンにコピーします。

Create(IFormatProvider, DefaultInterpolatedStringHandler)

指定したプロバイダーを使用して、指定した補間文字列の書式設定を制御することで、新しい文字列を作成します。

Create(IFormatProvider, Span<Char>, DefaultInterpolatedStringHandler)

指定したプロバイダーを使用して、指定した補間文字列の書式設定を制御することで、新しい文字列を作成します。

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

特定の長さの新しい文字列を作成し、作成後に指定したコールバックを使用してそれを初期化します。

EndsWith(Char)

この文字列インスタンスの末尾が、指定した文字と一致するかどうかを判断します。

EndsWith(String)

この文字列インスタンスの末尾が、指定した文字列と一致するかどうかを判断します。

EndsWith(String, Boolean, CultureInfo)

指定されたカルチャを使って比較した場合に、この文字列インスタンスの末尾が、指定された文字列と一致するかどうかを判断します。

EndsWith(String, StringComparison)

指定された比較オプションを使って比較した場合に、この文字列インスタンスの末尾が、指定された文字列と一致するかどうかを判断します。

EnumerateRunes()

この文字列から Rune の列挙体を返します。

Equals(Object)

このインスタンスと、指定したオブジェクトの値が同一かどうかを判断します。String オブジェクトを指定する必要があります。

Equals(String)

このインスタンスと、指定した別の String の値が同一かどうかを判断します。

Equals(String, String)

指定した 2 つの String オブジェクトの値が同一かどうかを判断します。

Equals(String, String, StringComparison)

指定した 2 つの String オブジェクトの値が同一かどうかを判断します。 比較に使用するカルチャ、大文字と小文字の区別、および、並べ替え規則をパラメーターで指定します。

Equals(String, StringComparison)

この文字列と、指定した String オブジェクトの値が同一かどうかを判断します。 比較に使用するカルチャ、大文字と小文字の区別、および、並べ替え規則をパラメーターで指定します。

Format(IFormatProvider, CompositeFormat, Object[])

テキストを一連の UTF-16 コード単位として表現します。

Format(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

テキストを一連の UTF-16 コード単位として表現します。

Format(IFormatProvider, String, Object)

指定した文字列の 1 つまたは複数の書式項目を、対応するオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。

Format(IFormatProvider, String, Object, Object)

文字列の書式項目を、指定した 2 つのオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。

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

文字列の書式項目を、指定した 3 つのオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式設定情報を指定します。

Format(IFormatProvider, String, Object[])

文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列表記に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。

Format(String, Object)

文字列の 1 つ以上の書式項目を、指定されたオブジェクトの文字列表記に置換します。

Format(String, Object, Object)

文字列の書式項目を、指定した 2 つのオブジェクトの文字列形式に置換します。

Format(String, Object, Object, Object)

文字列の書式項目を、指定した 3 つのオブジェクトの文字列形式に置換します。

Format(String, Object[])

指定した文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列形式に置換します。

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

テキストを一連の UTF-16 コード単位として表現します。

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

テキストを一連の UTF-16 コード単位として表現します。

Format<TArg0>(IFormatProvider, CompositeFormat, TArg0)

テキストを一連の UTF-16 コード単位として表現します。

GetEnumerator()

この文字列に含まれる個々の文字を反復処理するオブジェクトを取得します。

GetHashCode()

この文字列のハッシュ コードを返します。

GetHashCode(ReadOnlySpan<Char>)

指定された読み取り専用文字スパンのハッシュ コードを返します。

GetHashCode(ReadOnlySpan<Char>, StringComparison)

指定された規則を使用して、指定された読み取り専用の文字スパンのハッシュ コードを返します。

GetHashCode(StringComparison)

指定された規則を使用して、この文字列のハッシュ コードを返します。

GetPinnableReference()

インデックス 0 にある文字列の要素への参照を返します。

このメソッドは.NET コンパイラをサポートすることを目的としており、ユーザー コードによって呼び出されるものではありません。

GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
GetTypeCode()

String クラスには TypeCode を返します。

IndexOf(Char)

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。

IndexOf(Char, Int32)

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

IndexOf(Char, Int32, Int32)

指定文字がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

IndexOf(Char, StringComparison)

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 指定した文字に使用する検索の種類をパラメーターで指定します。

IndexOf(String)

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。

IndexOf(String, Int32)

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

IndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

IndexOf(String, Int32, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 現在の文字列での検索開始位置、現在の文字列で検索する文字の数、および指定した文字列に使用する検索の種類をパラメーターで指定します。

IndexOf(String, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 現在の文字列内での検索の開始位置、および指定した文字列に使用する検索の種類をパラメーターで指定します。

IndexOf(String, StringComparison)

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 指定した文字列に使用する検索の種類をパラメーターで指定します。

IndexOfAny(Char[])

Unicode 文字の指定した配列内にある文字がこのインスタンスで最初に見つかった位置の 0 から始まるインデックスをレポートします。

IndexOfAny(Char[], Int32)

Unicode 文字の指定した配列内にある文字がこのインスタンスで最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

IndexOfAny(Char[], Int32, Int32)

Unicode 文字の指定した配列内にある文字がこのインスタンスで最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

Insert(Int32, String)

このインスタンス内の指定したインデックス位置に指定した文字列を挿入する場合の、新しい文字列を返します。

Intern(String)

指定した String へのシステム参照を取得します。

IsInterned(String)

指定した String への参照を取得します。

IsNormalized()

この文字列が、Unicode 正規形 C であるかどうかを示します。

IsNormalized(NormalizationForm)

この文字列が、指定された Unicode 正規形であるかどうかを示します。

IsNullOrEmpty(String)

指定された文字列が null または空の文字列 ("") であるかどうかを示します。

IsNullOrWhiteSpace(String)

指定された文字列が null または空であるか、空白文字だけで構成されているかどうかを示します。

Join(Char, Object[])

各メンバー間に指定した区切り記号を使用して、オブジェクトの配列の文字列表現を連結します。

Join(Char, String[])

各メンバー間に指定した区切り記号を使用して、文字列の配列を連結します。

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

各メンバー間に指定した区切り記号を使用して、文字列の配列を連結します。startIndex の位置に配置された value 内の要素から開始し、count 要素までを連結します。

Join(String, IEnumerable<String>)

IEnumerable<T> 型の構築された String コレクションのメンバーを連結します。各メンバーの間には、指定した区切り記号が挿入されます。

Join(String, Object[])

オブジェクト配列の要素を連結します。各要素の間には、指定した区切り記号が挿入されます。

Join(String, String[])

文字列配列のすべての要素を連結します。各要素の間には、指定した区切り記号が挿入されます。

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

文字列配列の指定した要素を連結します。各要素の間には、指定した区切り記号が挿入されます。

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

コレクションのメンバーを連結します。各メンバーの間には、指定した区切り記号が挿入されます。

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

コレクションのメンバーを連結します。各メンバーの間には、指定した区切り記号が挿入されます。

LastIndexOf(Char)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。

LastIndexOf(Char, Int32)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。

LastIndexOf(Char, Int32, Int32)

このインスタンス内の部分文字列で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

LastIndexOf(String)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。

LastIndexOf(String, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。

LastIndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

LastIndexOf(String, Int32, Int32, StringComparison)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。

LastIndexOf(String, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最後に見つかった 0 から始まる位置のインデックスをレポートします。 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。

LastIndexOf(String, StringComparison)

指定した文字列が現在の String オブジェクト内で最後に見つかった 0 から始まる位置のインデックスをレポートします。 指定した文字列に使用する検索の種類をパラメーターで指定します。

LastIndexOfAny(Char[])

Unicode 配列内の指定した 1 つ以上の文字がこのインスタンスで最後に見つかった 0 から始まるインデックス位置をレポートします。

LastIndexOfAny(Char[], Int32)

Unicode 配列内の指定した 1 つ以上の文字がこのインスタンスで最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。

LastIndexOfAny(Char[], Int32, Int32)

Unicode 配列内の指定した 1 つ以上の文字がこのインスタンスで最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
Normalize()

この文字列と同じテキスト値を持ち、なおかつ、バイナリ表現が Unicode 正規形 C である新しい文字列を返します。

Normalize(NormalizationForm)

この文字列と同じテキスト値を持ち、なおかつ、バイナリ表現が、指定された Unicode 正規形である新しい文字列を返します。

PadLeft(Int32)

指定された文字数になるまで左側に空白を埋め込むことで、このインスタンス内の文字を右寄せした新しい文字列を返します。

PadLeft(Int32, Char)

指定された文字数になるまで左側に指定された Unicode 文字を埋め込むことで、このインスタンス内の文字を右寄せした新しい文字列を返します。

PadRight(Int32)

指定された文字数になるまで右側に空白を埋め込むことで、この文字列内の文字を左寄せした新しい文字列を返します。

PadRight(Int32, Char)

指定された文字数になるまで右側に指定された Unicode 文字を埋め込むことで、この文字列内の文字を左寄せした新しい文字列を返します。

Remove(Int32)

現在のインスタンスの指定した位置から指定した最後の位置までの全文字が削除された新しい文字列を返します。

Remove(Int32, Int32)

現在のインスタンス内の指定した位置から指定した文字数が削除された新しい文字列を返します。

Replace(Char, Char)

このインスタンスに出現する指定された Unicode 文字をすべて、別の指定された Unicode 文字に置換した新しい文字列を返します。

Replace(String, String)

現在のインスタンスに出現する指定した文字列をすべて、別に指定した文字列に置換した新しい文字列を返します。

Replace(String, String, Boolean, CultureInfo)

指定されたカルチャおよび大文字と小文字の区別を使用して、現在のインスタンスに出現する指定した文字列をすべて、別に指定した文字列に置換した新しい文字列を返します。

Replace(String, String, StringComparison)

指定された比較型を使用して、現在のインスタンスに出現する指定した文字列をすべて、別に指定した文字列に置換した新しい文字列を返します。

ReplaceLineEndings()

現在の文字列内のすべての改行シーケンスを に置き NewLine換えます。

ReplaceLineEndings(String)

現在の文字列内のすべての改行シーケンスを に置き replacementText換えます。

Split(Char, Int32, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。 指定された文字区切り記号に基づいて文字列を最大数の部分文字列に分割します。オプションで、結果からの空の部分文字列を省略します。

Split(Char, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を部分文字列に分割します。

Split(Char[])

指定した区切り文字に基づいて、文字列を部分文字列に分割します。

Split(Char[], Int32)

指定した区切り文字に基づいて、文字列を部分文字列の最大数に分割します。

Split(Char[], Int32, StringSplitOptions)

指定された区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

Split(Char[], StringSplitOptions)

指定した区切り文字とオプションに基づいて、文字列を部分文字列に分割します。

Split(String, Int32, StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

Split(String, StringSplitOptions)

指定された文字列の区切り記号に基づいて文字列を部分文字列に分割します。

Split(String[], Int32, StringSplitOptions)

指定された区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

Split(String[], StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を部分文字列に分割します。

StartsWith(Char)

この文字列インスタンスが指定した文字で始まっているかどうかを判断します。

StartsWith(String)

この文字列インスタンスの先頭が、指定した文字列と一致するかどうかを判断します。

StartsWith(String, Boolean, CultureInfo)

指定されたカルチャを使って比較した場合に、この文字列インスタンスの先頭が、指定された文字列と一致するかどうかを判断します。

StartsWith(String, StringComparison)

指定された比較オプションを使って比較した場合に、この文字列インスタンスの先頭が、指定された文字列と一致するかどうかを判断します。

Substring(Int32)

インスタンスから部分文字列を取得します。 部分文字列は、文字列中の指定した文字の位置で開始し、文字列の末尾まで続きます。

Substring(Int32, Int32)

インスタンスから部分文字列を取得します。 この部分文字列は、指定した文字位置から開始し、指定した文字数の文字列です。

ToCharArray()

このインスタンスの文字を Unicode 文字配列へコピーします。

ToCharArray(Int32, Int32)

このインスタンスの指定した部分文字列の文字を Unicode 文字配列へコピーします。

ToLower()

この文字列のコピーを小文字に変換して返します。

ToLower(CultureInfo)

指定されたカルチャの大文字と小文字の規則を使用して、この文字列のコピーを小文字に変換して返します。

ToLowerInvariant()

インバリアント カルチャの大文字と小文字の規則を使用して、この String オブジェクトのコピーを小文字に変換して返します。

ToString()

String のこのインスタンスを返します。実際の変換処理は実行されません。

ToString(IFormatProvider)

String のこのインスタンスを返します。実際の変換処理は実行されません。

ToUpper()

この文字列のコピーを大文字に変換して返します。

ToUpper(CultureInfo)

指定されたカルチャの大文字と小文字の規則を使用して、この文字列のコピーを大文字に変換して返します。

ToUpperInvariant()

インバリアント カルチャの大文字と小文字の規則を使用して、この String オブジェクトのコピーを大文字に変換して返します。

Trim()

現在の文字列から、先頭および末尾にある空白文字をすべて削除します。

Trim(Char)

現在の文字列から、文字の先頭および末尾のインスタンスをすべて削除します。

Trim(Char[])

現在の文字列から、配列で指定された一連の文字が先頭および末尾に現れる箇所をすべて削除します。

TrimEnd()

現在の文字列から末尾の空白文字をすべて削除します。

TrimEnd(Char)

現在の文字列から、末尾に出現する文字をすべて削除します。

TrimEnd(Char[])

現在の文字列から、配列で指定された一連の文字が末尾に現れる箇所をすべて削除します。

TrimStart()

現在の文字列から先頭の空白文字をすべて削除します。

TrimStart(Char)

現在の文字列から、指定した文字が先頭に現れる箇所をすべて削除します。

TrimStart(Char[])

現在の文字列から、配列で指定された一連の文字が先頭に現れる箇所をすべて削除します。

TryCopyTo(Span<Char>)

この文字列の内容をコピー先スパンにコピーします。

演算子

Equality(String, String)

指定した 2 つの文字列の値が同一かどうかを判断します。

Implicit(String to ReadOnlySpan<Char>)

指定された文字列から文字の読み取り専用スパンへの暗黙的な変換を定義します。

Inequality(String, String)

指定した 2 つの文字列の値が異なるかどうかを判断します。

明示的なインターフェイスの実装

IComparable.CompareTo(Object)

このインスタンスと指定した Object とを比較し、並べ替え順序において、このインスタンスの位置が指定した Object の前、後ろ、または同じのいずれであるかを示します。

IConvertible.GetTypeCode()

String クラスには TypeCode を返します。

IConvertible.ToBoolean(IFormatProvider)

このメンバーの詳細については、「ToBoolean(IFormatProvider)」をご覧ください。

IConvertible.ToByte(IFormatProvider)

このメンバーの詳細については、「ToByte(IFormatProvider)」をご覧ください。

IConvertible.ToChar(IFormatProvider)

このメンバーの詳細については、「ToChar(IFormatProvider)」をご覧ください。

IConvertible.ToDateTime(IFormatProvider)

このメンバーの詳細については、「ToDateTime(IFormatProvider)」をご覧ください。

IConvertible.ToDecimal(IFormatProvider)

このメンバーの詳細については、「ToDecimal(IFormatProvider)」をご覧ください。

IConvertible.ToDouble(IFormatProvider)

このメンバーの詳細については、「ToDouble(IFormatProvider)」をご覧ください。

IConvertible.ToInt16(IFormatProvider)

このメンバーの詳細については、「ToInt16(IFormatProvider)」をご覧ください。

IConvertible.ToInt32(IFormatProvider)

このメンバーの詳細については、「ToInt32(IFormatProvider)」をご覧ください。

IConvertible.ToInt64(IFormatProvider)

このメンバーの詳細については、「ToInt64(IFormatProvider)」をご覧ください。

IConvertible.ToSByte(IFormatProvider)

このメンバーの詳細については、「ToSByte(IFormatProvider)」をご覧ください。

IConvertible.ToSingle(IFormatProvider)

このメンバーの詳細については、「ToSingle(IFormatProvider)」をご覧ください。

IConvertible.ToString(IFormatProvider)

このメンバーの詳細については、「ToString(IFormatProvider)」をご覧ください。

IConvertible.ToType(Type, IFormatProvider)

このメンバーの詳細については、「ToType(Type, IFormatProvider)」をご覧ください。

IConvertible.ToUInt16(IFormatProvider)

このメンバーの詳細については、「ToUInt16(IFormatProvider)」をご覧ください。

IConvertible.ToUInt32(IFormatProvider)

このメンバーの詳細については、「ToUInt32(IFormatProvider)」をご覧ください。

IConvertible.ToUInt64(IFormatProvider)

このメンバーの詳細については、「ToUInt64(IFormatProvider)」をご覧ください。

IEnumerable.GetEnumerator()

現在の String オブジェクトを反復処理する列挙子を返します。

IEnumerable<Char>.GetEnumerator()

現在の String オブジェクトを反復処理する列挙子を返します。

IParsable<String>.Parse(String, IFormatProvider)

テキストを一連の UTF-16 コード単位として表現します。

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

テキストを一連の UTF-16 コード単位として表現します。

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

テキストを一連の UTF-16 コード単位として表現します。

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

テキストを一連の UTF-16 コード単位として表現します。

拡張メソッド

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

テキストを一連の UTF-16 コード単位として表現します。

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

テキストを一連の UTF-16 コード単位として表現します。

ToFrozenSet<T>(IEnumerable<T>, Boolean)

テキストを一連の UTF-16 コード単位として表現します。

ToFrozenSet<T>(IEnumerable<T>, IEqualityComparer<T>)

テキストを一連の UTF-16 コード単位として表現します。

ToFrozenSet<T>(IEnumerable<T>, IEqualityComparer<T>, Boolean)

テキストを一連の UTF-16 コード単位として表現します。

ToImmutableArray<TSource>(IEnumerable<TSource>)

指定されたコレクションから、変更できない配列を作成します。

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

ソース キーに変換関数を適用し、変更できないディクショナリを既存の要素のコレクションから作成します。

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

シーケンスの変換に基づき、変更できないディクショナリを作成します。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

シーケンスを列挙して変換し、その内容の変更できないディクショナリを生成します。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>)

シーケンスを列挙して変換し、指定されたキーの比較子を使用してその内容の変更できないディクショナリを生成します。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>)

シーケンスを列挙して変換し、指定されたキーの比較子および値の比較子を使用してその内容の変更できないディクショナリを生成します。

ToImmutableHashSet<TSource>(IEnumerable<TSource>)

シーケンスを列挙し、その内容の変更できないハッシュ セットを生成します。

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

シーケンスを列挙し、その内容の変更できないハッシュ セットを生成して、指定された等値比較子をセットの種類に使用します。

ToImmutableList<TSource>(IEnumerable<TSource>)

シーケンスを列挙し、その内容の変更できないリストを生成します。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

シーケンスを列挙して変換し、その内容の変更できない並べ替えられたディクショナリを生成します。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>)

シーケンスを列挙して変換し、指定されたキーの比較子を使用してその内容の変更できない並べ替えられたディクショナリを生成します。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>)

シーケンスを列挙して変換し、指定されたキーの比較子と値の比較子を使用してその内容の変更できない並べ替えられたディクショナリを生成します。

ToImmutableSortedSet<TSource>(IEnumerable<TSource>)

シーケンスを列挙し、その内容の変更できない並べ替えられたセットを生成します。

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

シーケンスを列挙し、その内容の変更できない並べ替えられたセットを生成して、指定された比較子を使用します。

CopyToDataTable<T>(IEnumerable<T>)

指定した入力 DataTable オブジェクトに応じて (ジェネリック パラメーター TDataRow)、IEnumerable<T> オブジェクトのコピーを格納する DataRow を返します。

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

指定した入力 DataRow オブジェクトに応じて (ジェネリック パラメーター TDataTable)、指定した IEnumerable<T>DataRow オブジェクトをコピーします。

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

指定した入力 DataRow オブジェクトに応じて (ジェネリック パラメーター TDataTable)、指定した IEnumerable<T>DataRow オブジェクトをコピーします。

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

シーケンスにアキュムレータ関数を適用します。

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

シーケンスにアキュムレータ関数を適用します。 指定されたシード値が最初のアキュムレータ値として使用されます。

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

シーケンスにアキュムレータ関数を適用します。 指定したシード値は最初のアキュムレータ値として使用され、指定した関数は結果値の選択に使用されます。

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

シーケンスのすべての要素が条件を満たしているかどうかを判断します。

Any<TSource>(IEnumerable<TSource>)

シーケンスに要素が含まれているかどうかを判断します。

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

シーケンスの任意の要素が条件を満たしているかどうかを判断します。

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

シーケンスの末尾に値を追加します。

AsEnumerable<TSource>(IEnumerable<TSource>)

IEnumerable<T> として型指定された入力を返します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Decimal 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Double 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Int32 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Int64 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Decimal 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Double 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Int32 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Int64 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Single 値のシーケンスの平均値を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Single 値のシーケンスの平均値を計算します。

Cast<TResult>(IEnumerable)

IEnumerable の要素を、指定した型にキャストします。

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

シーケンスの要素を最大サイズの sizeチャンクに分割します。

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

2 つのシーケンスを連結します。

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

既定の等値比較子を使用して、指定した要素がシーケンスに含まれているかどうかを判断します。

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

指定した IEqualityComparer<T> を使用して、指定した要素がシーケンスに含まれているかどうかを判断します。

Count<TSource>(IEnumerable<TSource>)

シーケンス内の要素数を返します。

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

条件を満たす、指定されたシーケンス内の要素の数を表す数値を返します。

DefaultIfEmpty<TSource>(IEnumerable<TSource>)

指定したシーケンスの要素を返します。シーケンスが空の場合はシングルトン コレクションにある型パラメーターの既定値を返します。

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

指定されたシーケンスの要素を返します。シーケンスが空の場合はシングルトン コレクションにある型パラメーターの既定値を返します。

Distinct<TSource>(IEnumerable<TSource>)

既定の等値比較子を使用して値を比較することにより、シーケンスから一意の要素を返します。

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

指定された IEqualityComparer<T> を使用して値を比較することにより、シーケンスから一意の要素を返します。

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

指定したキー セレクター関数に従って、シーケンスから個別の要素を返します。

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

指定したキー セレクター関数に従ってシーケンスから個別の要素を返し、指定した比較子を使用してキーを比較します。

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

シーケンス内の指定されたインデックス位置にある要素を返します。

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

シーケンス内の指定されたインデックス位置にある要素を返します。

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

シーケンス内の指定したインデックス位置にある要素を返します。インデックスが範囲外の場合は既定値を返します。

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

シーケンス内の指定したインデックス位置にある要素を返します。インデックスが範囲外の場合は既定値を返します。

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

既定の等値比較子を使用して値を比較することにより、2 つのシーケンスの差集合を生成します。

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

指定された IEqualityComparer<T> を使用して値を比較することにより、2 つのシーケンスの差集合を生成します。

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

指定したキー セレクター関数に従って、2 つのシーケンスのセット差を生成します。

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

指定したキー セレクター関数に従って、2 つのシーケンスのセット差を生成します。

First<TSource>(IEnumerable<TSource>)

シーケンスの最初の要素を返します。

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

指定された条件を満たす、シーケンスの最初の要素を返します。

FirstOrDefault<TSource>(IEnumerable<TSource>)

シーケンスの最初の要素を返します。シーケンスに要素が含まれていない場合は既定値を返します。

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

シーケンスの最初の要素を返します。シーケンスに要素が含まれない場合は、指定した既定値を返します。

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

条件を満たす、シーケンスの最初の要素を返します。このような要素が見つからない場合は既定値を返します。

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

条件を満たすシーケンスの最初の要素、またはそのような要素が見つからない場合は、指定された既定値を返します。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化します。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化し、指定された比較子を使用してキーを比較します。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化し、指定された関数を使用して各グループの要素を射影します。

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

キー セレクター関数に従ってシーケンスの要素をグループ化します。 キーの比較には、比較子を使用し、各グループの要素の射影には、指定された関数を使用します。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化し、各グループとそのキーから結果値を作成します。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化し、各グループとそのキーから結果値を作成します。 キーの比較には、指定された比較子を使用します。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化し、各グループとそのキーから結果値を作成します。 各グループの要素は、指定された関数を使用して射影されます。

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

指定されたキー セレクター関数に従ってシーケンスの要素をグループ化し、各グループとそのキーから結果値を作成します。 キー値の比較には、指定された比較子を使用し、各グループの要素の射影には、指定された関数を使用します。

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

キーが等しいかどうかに基づいて 2 つのシーケンスの要素を相互に関連付け、その結果をグループ化します。 キーの比較には既定の等値比較子が使用されます。

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

キーが等しいかどうかに基づいて 2 つのシーケンスの要素を相互に関連付け、その結果をグループ化します。 指定された IEqualityComparer<T> を使用してキーを比較します。

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

既定の等値比較子を使用して値を比較することにより、2 つのシーケンスの積集合を生成します。

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

指定された IEqualityComparer<T> を使用して値を比較することにより、2 つのシーケンスの積集合を生成します。

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

指定したキー セレクター関数に従って、2 つのシーケンスの集合積集合を生成します。

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

指定したキー セレクター関数に従って、2 つのシーケンスの集合積集合を生成します。

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

一致するキーに基づいて 2 つのシーケンスの要素を相互に関連付けます。 キーの比較には既定の等値比較子が使用されます。

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

一致するキーに基づいて 2 つのシーケンスの要素を相互に関連付けます。 指定された IEqualityComparer<T> を使用してキーを比較します。

Last<TSource>(IEnumerable<TSource>)

シーケンスの最後の要素を返します。

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

指定された条件を満たす、シーケンスの最後の要素を返します。

LastOrDefault<TSource>(IEnumerable<TSource>)

シーケンスの最後の要素を返します。シーケンスに要素が含まれていない場合は既定値を返します。

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

シーケンスの最後の要素を返します。シーケンスに要素が含まれない場合は、指定した既定値を返します。

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

条件を満たす、シーケンスの最後の要素を返します。このような要素が見つからない場合は既定値を返します。

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

条件を満たすシーケンスの最後の要素、またはそのような要素が見つからない場合は、指定された既定値を返します。

LongCount<TSource>(IEnumerable<TSource>)

シーケンス内の要素の合計数を表す Int64 を返します。

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

シーケンス内で条件を満たす要素の数を表す Int64 を返します。

Max<TSource>(IEnumerable<TSource>)

ジェネリック シーケンスの最大値を返します。

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

ジェネリック シーケンスの最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Decimal の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Double の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Int32 の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Int64 の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Decimal の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Double の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Int32 の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Int64 の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Single の最大値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Single の最大値を返します。

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

ジェネリック シーケンスの各要素に対して変換関数を呼び出し、結果の最大値を返します。

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

指定したキー セレクター関数に従って、ジェネリック シーケンスの最大値を返します。

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

指定したキー セレクター関数とキー比較子に従って、ジェネリック シーケンスの最大値を返します。

Min<TSource>(IEnumerable<TSource>)

ジェネリック シーケンスの最小値を返します。

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

ジェネリック シーケンスの最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Decimal の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Double の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Int32 の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Int64 の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Decimal の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Double の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Int32 の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Int64 の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、null 許容の Single の最小値を返します。

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

シーケンスの各要素に対して変換関数を呼び出し、Single の最小値を返します。

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

ジェネリック シーケンスの各要素に対して変換関数を呼び出し、結果の最小値を返します。

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

指定したキー セレクター関数に従って、ジェネリック シーケンスの最小値を返します。

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

指定したキー セレクター関数とキー比較子に従って、ジェネリック シーケンスの最小値を返します。

OfType<TResult>(IEnumerable)

指定された型に基づいて IEnumerable の要素をフィルター処理します。

Order<T>(IEnumerable<T>)

シーケンスの要素を昇順に並べ替えます。

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

シーケンスの要素を昇順に並べ替えます。

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

シーケンスの要素をキーに従って昇順に並べ替えます。

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

指定された比較子を使用してシーケンスの要素を昇順に並べ替えます。

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

シーケンスの要素をキーに従って降順に並べ替えます。

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

指定された比較子を使用してシーケンスの要素を降順に並べ替えます。

OrderDescending<T>(IEnumerable<T>)

シーケンスの要素を降順に並べ替えます。

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

シーケンスの要素を降順に並べ替えます。

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

シーケンスの先頭に値を追加します。

Reverse<TSource>(IEnumerable<TSource>)

シーケンスの要素の順序を反転させます。

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

シーケンスの各要素を新しいフォームに射影します。

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

要素のインデックスを組み込むことにより、シーケンスの各要素を新しいフォームに射影します。

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

シーケンスの各要素を IEnumerable<T> に射影し、結果のシーケンスを 1 つのシーケンスに平坦化します。

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

シーケンスの各要素を IEnumerable<T> に射影し、結果のシーケンスを 1 つのシーケンスに平坦化します。 各ソース要素のインデックスは、その要素の射影されたフォームで使用されます。

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

シーケンスの各要素を IEnumerable<T> に射影し、結果のシーケンスを 1 つのシーケンスに平坦化して、その各要素に対して結果のセレクター関数を呼び出します。

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

シーケンスの各要素を IEnumerable<T> に射影し、結果のシーケンスを 1 つのシーケンスに平坦化して、その各要素に対して結果のセレクター関数を呼び出します。 各ソース要素のインデックスは、その要素の中間の射影されたフォームで使用されます。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

要素の型に対して既定の等値比較子を使用して要素を比較することで、2 つのシーケンスが等しいかどうかを判断します。

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

指定された IEqualityComparer<T> を使用して要素を比較することで、2 つのシーケンスが等しいかどうかを判断します。

Single<TSource>(IEnumerable<TSource>)

シーケンスの唯一の要素を返し、シーケンス内の要素が 1 つだけでない場合は例外をスローします。

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

指定された条件を満たす、シーケンスの唯一の要素を返し、そのような要素が複数存在する場合は例外をスローします。

SingleOrDefault<TSource>(IEnumerable<TSource>)

シーケンスの唯一の要素を返します。シーケンスが空の場合、既定値を返します。シーケンス内に要素が複数ある場合、このメソッドは例外をスローします。

SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)

シーケンスの唯一の要素を返します。シーケンスが空の場合は、指定された既定値を返します。シーケンス内に複数の要素がある場合、このメソッドは例外をスローします。

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

指定された条件を満たすシーケンスの唯一の要素、またはそのような要素がない場合は既定値を返します。このメソッドは、複数の要素が条件を満たす場合に例外をスローします。

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

指定した条件を満たすシーケンスの唯一の要素、またはそのような要素が存在しない場合は、指定された既定値を返します。このメソッドは、複数の要素が条件を満たす場合に例外をスローします。

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

シーケンス内の指定された数の要素をバイパスし、残りの要素を返します。

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

source の要素と、省略されたソース コレクションの最後の count 要素を含む、列挙可能な新しいコレクションを返します。

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

指定された条件が満たされる限り、シーケンスの要素をバイパスした後、残りの要素を返します。

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

指定された条件が満たされる限り、シーケンスの要素をバイパスした後、残りの要素を返します。 要素のインデックスは、述語関数のロジックで使用されます。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Decimal 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Double 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Int32 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Int64 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Decimal 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Double 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Int32 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Int64 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する null 許容の Single 値のシーケンスの合計を計算します。

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

入力シーケンスの各要素に対して変換関数を呼び出して取得する Single 値のシーケンスの合計を計算します。

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

シーケンスの先頭から、指定された数の連続する要素を返します。

Take<TSource>(IEnumerable<TSource>, Range)

シーケンスから指定した連続する要素の範囲を返します。

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

source の最後の count 要素を含む、列挙可能な新しいコレクションを返します。

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

指定された条件が満たされる限り、シーケンスから要素を返します。

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

指定された条件が満たされる限り、シーケンスから要素を返します。 要素のインデックスは、述語関数のロジックで使用されます。

ToArray<TSource>(IEnumerable<TSource>)

IEnumerable<T> から配列を作成します。

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

指定されたキー セレクター関数に従って、Dictionary<TKey,TValue> から IEnumerable<T> を作成します。

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

指定されたキー セレクター関数およびキーの比較子に従って、Dictionary<TKey,TValue> から IEnumerable<T> を作成します。

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

指定されたキー セレクター関数および要素セレクター関数に従って、Dictionary<TKey,TValue> から IEnumerable<T> を作成します。

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

指定されたキー セレクター関数、比較子、および要素セレクター関数に従って、Dictionary<TKey,TValue> から IEnumerable<T> を作成します。

ToHashSet<TSource>(IEnumerable<TSource>)

IEnumerable<T> から HashSet<T> を作成します。

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

comparer を使用して IEnumerable<T>から HashSet<T> を作成し、キーを比較します。

ToList<TSource>(IEnumerable<TSource>)

IEnumerable<T> から List<T> を作成します。

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

指定されたキー セレクター関数に従って、Lookup<TKey,TElement> から IEnumerable<T> を作成します。

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

指定されたキー セレクター関数およびキーの比較子に従って、Lookup<TKey,TElement> から IEnumerable<T> を作成します。

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

指定されたキー セレクター関数および要素セレクター関数に従って、Lookup<TKey,TElement> から IEnumerable<T> を作成します。

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

指定されたキー セレクター関数、比較子、および要素セレクター関数に従って、Lookup<TKey,TElement> から IEnumerable<T> を作成します。

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

列挙型を強制せずに、シーケンス内の要素の数の測定を試みます。

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

既定の等値比較子を使用して、2 つのシーケンスの和集合を生成します。

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

指定された IEqualityComparer<T> を使用して 2 つのシーケンスの和集合を生成します。

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

指定したキー セレクター関数に従って、2 つのシーケンスのセット和集合を生成します。

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

指定したキー セレクター関数に従って、2 つのシーケンスのセット和集合を生成します。

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

述語に基づいて値のシーケンスをフィルター処理します。

Where<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

述語に基づいて値のシーケンスをフィルター処理します。 各要素のインデックスは、述語関数のロジックで使用されます。

Zip<TFirst,TSecond>(IEnumerable<TFirst>, IEnumerable<TSecond>)

指定された 2 つのシーケンスの要素を持つタプルのシーケンスを生成します。

Zip<TFirst,TSecond,TThird>(IEnumerable<TFirst>, IEnumerable<TSecond>, IEnumerable<TThird>)

指定した 3 つのシーケンスの要素を含むタプルのシーケンスを生成します。

Zip<TFirst,TSecond,TResult>(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst,TSecond,TResult>)

2 つのシーケンスの対応する要素に対して、1 つの指定した関数を適用し、結果として 1 つのシーケンスを生成します。

AsParallel(IEnumerable)

クエリの並列化を有効にします。

AsParallel<TSource>(IEnumerable<TSource>)

クエリの並列化を有効にします。

AsQueryable(IEnumerable)

IEnumerableIQueryable に変換します。

AsQueryable<TElement>(IEnumerable<TElement>)

ジェネリックの IEnumerable<T> をジェネリックの IQueryable<T> に変換します。

AsMemory(String)

挿入先の文字列の一部に新しい ReadOnlyMemory<Char> を作成します。

AsMemory(String, Index)

指定したインデックスを開始位置として、挿入先の文字列の一部に対して新しい ReadOnlyMemory<Char> を作成します。

AsMemory(String, Int32)

指定した文字位置を開始位置として、挿入先の文字列の一部に対して新しい ReadOnlyMemory<Char> を作成します。

AsMemory(String, Int32, Int32)

指定した位置 (長さを含む) を開始位置として、挿入先の文字列の一部に対して新しい ReadOnlyMemory<Char> を作成します。

AsMemory(String, Range)

挿入先の文字列の指定範囲に新しい ReadOnlyMemory<Char> を作成します。

AsSpan(String)

文字列に対して新しい読み取り専用のスパンを作成します。

AsSpan(String, Index)

テキストを一連の UTF-16 コード単位として表現します。

AsSpan(String, Int32)

指定された位置から文字列の終わりまで、挿入先の文字列の一部に対して読み取り専用の新しい範囲を作成します。

AsSpan(String, Int32, Int32)

指定された位置から指定された文字数だけ、挿入先の文字列の一部に対して読み取り専用の新しい範囲を作成します。

AsSpan(String, Range)

テキストを一連の UTF-16 コード単位として表現します。

IsNormalized(String)

指定された文字列が、Unicode 正規形 C であるかどうかを示します。

IsNormalized(String, NormalizationForm)

文字列が指定された Unicode 正規形であるかどうかを示します。

Normalize(String)

文字列を Unicode 正規形 C に正規化します。

Normalize(String, NormalizationForm)

文字列を、指定された Unicode 正規形に正規化します。

Ancestors<T>(IEnumerable<T>)

ソース コレクション内のすべてのノードの先祖が格納された、要素のコレクションを返します。

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

ソース コレクション内のすべてのノードの先祖が格納され、フィルター処理された要素のコレクションを返します。 一致する XName を持つ要素のみがコレクションに含められます。

DescendantNodes<T>(IEnumerable<T>)

ソース コレクション内のすべてのドキュメントおよび要素の子孫ノードのコレクションを返します。

Descendants<T>(IEnumerable<T>)

ソース コレクション内のすべての要素とドキュメントの子孫要素が格納された要素のコレクションを返します。

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

ソース コレクション内のすべての要素とドキュメントの子孫要素が格納され、フィルター処理された要素のコレクションを返します。 一致する XName を持つ要素のみがコレクションに含められます。

Elements<T>(IEnumerable<T>)

ソース コレクション内のすべての要素およびドキュメントの子要素のコレクションを返します。

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

ソース コレクション内のすべての要素およびドキュメントの、フィルター処理された子要素のコレクションを返します。 一致する XName を持つ要素のみがコレクションに含められます。

InDocumentOrder<T>(IEnumerable<T>)

ソース コレクション内のすべてのノードがドキュメント順に並べ替えて格納された、ノードのコレクションを返します。

Nodes<T>(IEnumerable<T>)

ソース コレクション内のすべてのドキュメントおよび要素の子ノードのコレクションを返します。

Remove<T>(IEnumerable<T>)

ソース コレクション内の親ノードからすべてのノードを削除します。

適用対象

スレッド セーフ

この型はスレッド セーフです。

こちらもご覧ください