[C#] String.Builder.CopTo 範例

轉自msdn

StringBuilder. CopyTo 方法


[ComVisibleAttribute(false)]
public void CopyTo(
    int sourceIndex,
    char[] destination,
    int destinationIndex,
    int count
)

參數

sourceIndex

型別: System. Int32
此執行個體中的開始位置,為字元的複製來源。 索引以零起始。
destination
型別: System. Char[]
將複製其中字元的陣列。
destinationIndex
型別: System. Int32
destination 中開始複製字元的位置。 索引以零起始。
count
型別: System. Int32
要複製的字元數。

  1. // This example demonstrates the CopyTo(Int32, Char[], Int32, Int32) method.
  2. // Typically the destination array is small, preallocated, and global while
  3. // the StringBuilder is large with programmatically defined data.
  4. // However, for this example both the array and StringBuilder are small
  5. // and the StringBuilder has predefined data.

  6. using System;
  7. using System.Text;
  8. class Sample
  9. {
  10.     protected static char[] dest = new char[6];
  11.     public static void Main()
  12.     {
  13.     StringBuilder src = new StringBuilder("abcdefghijklmnopqrstuvwxyz!");
  14.     dest[1] = ')';
  15.     dest[2] = ' ';
  16. // Copy the source to the destination in 9 pieces, 3 characters per piece.
  17.     Console.WriteLine("\nPiece) Data:");
  18.     for(int ix = 0; ix < 9; ix++)
  19.         {
  20.         dest[0] = ix.ToString()[0];
  21.         src.CopyTo(ix * 3, dest, 3, 3);
  22.         Console.Write("    ");
  23.         Console.WriteLine(dest);
  24.         }
  25.     }
  26. }
  27. /*
  28. This example produces the following results:
  29. Piece) Data:
  30.     0) abc
  31.     1) def
  32.     2) ghi
  33.     3) jkl
  34.     4) mno
  35.     5) pqr
  36.     6) stu
  37.     7) vwx
  38.     8) yz!
  39. */