StringBuilder.Chars[Int32] プロパティ

定義

このインスタンス内の指定した文字位置にある文字を取得または設定します。

public:
 property char default[int] { char get(int index); void set(int index, char value); };
public char this[int index] { get; set; }
member this.Chars(int) : char with get, set
Default Public Property Chars(index As Integer) As Char

パラメーター

index
Int32

文字の位置。

プロパティ値

位置 index Unicode 文字。

例外

index は、文字の設定中に、このインスタンスの範囲外です。

index は、文字を取得している間、このインスタンスの範囲外です。

注釈

index パラメーターは、StringBuilder内の文字の位置です。 文字列の最初の文字はインデックス 0 です。 文字列の長さは、文字列に含まれる文字数です。 StringBuilder インスタンスの最後にアクセスできる文字は、インデックス Length - 1 にあります。

Chars[Int32] は、 StringBuilder クラスの既定のプロパティです。 C# では、インデクサーです。 つまり、次の例に示すように、 Chars[Int32] プロパティから個々の文字を取得できます。このプロパティは、文字列内の英字、空白、句読点の文字の数をカウントします。

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      int nAlphabeticChars = 0;
      int nWhitespace = 0;
      int nPunctuation = 0;  
      StringBuilder sb = new StringBuilder("This is a simple sentence.");
      
      for (int ctr = 0; ctr < sb.Length; ctr++) {
         char ch = sb[ctr];
         if (Char.IsLetter(ch)) { nAlphabeticChars++;  continue; }
         if (Char.IsWhiteSpace(ch)) { nWhitespace++;  continue; }
         if (Char.IsPunctuation(ch)) nPunctuation++;  
      }    

      Console.WriteLine("The sentence '{0}' has:", sb);
      Console.WriteLine("   Alphabetic characters: {0}", nAlphabeticChars);
      Console.WriteLine("   White-space characters: {0}", nWhitespace);
      Console.WriteLine("   Punctuation characters: {0}", nPunctuation);
   }
}
// The example displays the following output:
//       The sentence 'This is a simple sentence.' has:
//          Alphabetic characters: 21
//          White-space characters: 4
//          Punctuation characters: 1
open System
open System.Text

let mutable nAlphabeticChars = 0
let mutable nWhitespace = 0
let mutable nPunctuation = 0  
let sb = StringBuilder "This is a simple sentence."

for i = 0 to sb.Length - 1 do
    let ch = sb[i]
    if Char.IsLetter ch then
        nAlphabeticChars <- nAlphabeticChars + 1
    elif Char.IsWhiteSpace ch then
        nWhitespace <- nWhitespace + 1
    elif Char.IsPunctuation ch then
        nPunctuation <- nPunctuation + 1

printfn $"The sentence '{sb}' has:"
printfn $"   Alphabetic characters: {nAlphabeticChars}"
printfn $"   White-space characters: {nWhitespace}"
printfn $"   Punctuation characters: {nPunctuation}"

// The example displays the following output:
//       The sentence 'This is a simple sentence.' has:
//          Alphabetic characters: 21
//          White-space characters: 4
//          Punctuation characters: 1
Imports System.Text

Module Example
   Public Sub Main()
      Dim nAlphabeticChars As Integer = 0
      Dim nWhitespace As Integer = 0
      Dim nPunctuation As Integer = 0  
      Dim sb As New StringBuilder("This is a simple sentence.")
      
      For ctr As Integer = 0 To sb.Length - 1
         Dim ch As Char = sb(ctr)
         If Char.IsLetter(ch) Then nAlphabeticChars += 1 : Continue For
         If Char.IsWhiteSpace(ch) Then nWhitespace += 1 : Continue For
         If Char.IsPunctuation(ch) Then nPunctuation += 1
      Next    

      Console.WriteLine("The sentence '{0}' has:", sb)
      Console.WriteLine("   Alphabetic characters: {0}", nAlphabeticChars)
      Console.WriteLine("   White-space characters: {0}", nWhitespace)
      Console.WriteLine("   Punctuation characters: {0}", nPunctuation)
   End Sub
End Module
' The example displays the following output:
'       The sentence 'This is a simple sentence.' has:
'          Alphabetic characters: 21
'          White-space characters: 4
'          Punctuation characters: 1

Chars[] プロパティで文字ベースのインデックス付けを使用すると、次の条件下では非常に遅くなることがあります。

  • StringBuilder インスタンスが大きい (たとえば、数万文字が含まれている)。
  • StringBuilderは "チャンク" です。つまり、StringBuilder.Appendなどのメソッドの呼び出しが繰り返されると、オブジェクトの StringBuilder.Capacity プロパティが自動的に拡張され、メモリの新しいチャンクが割り当てられます。

文字にアクセスするたびに、チャンクのリンク リスト全体が走査されて、インデックスを付ける適切なバッファーが検索されるため、パフォーマンスが著しく低下します。

Note

大きな "チャンク" StringBuilder オブジェクトの場合でも、1 つまたは少数の文字へのインデックス ベースのアクセスに Chars[] プロパティを使用すると、パフォーマンスに影響を与える可能性はごくわずかです。通常は、 O(n) 操作です。 StringBuilder オブジェクト内の文字を反復処理するときは、パフォーマンスに大きな影響が発生します。これは、O(n^2) 操作でます。

StringBuilder オブジェクトで文字ベースのインデックス付けを使うときにパフォーマンスの問題が発生する場合は、次のいずれかの回避策を使うことができます。

  • StringBuilder メソッドを呼び出して String インスタンスを ToString に変換した後、文字列内の文字にアクセスします。

  • 既存の StringBuilder オブジェクトの内容を、事前にサイズを設定した新しい StringBuilder オブジェクトにコピーします。 新しい StringBuilder オブジェクトはチャンク化していないため、パフォーマンスが向上します。 例えば次が挙げられます。

    // sbOriginal is the existing StringBuilder object
    var sbNew = new StringBuilder(sbOriginal.ToString(), sbOriginal.Length);
    
    ' sbOriginal is the existing StringBuilder object
    Dim sbNew = New StringBuilder(sbOriginal.ToString(), sbOriginal.Length)
    
  • StringBuilder コンストラクターを呼び出して、StringBuilder(Int32) オブジェクトの初期容量を、予想される最大サイズにほぼ等しい値に設定します。 このようにすると、StringBuilder が最大容量に達することがほとんどない場合であっても、メモリ ブロック全体が割り当てられることに注意してください。

適用対象

こちらもご覧ください