StringBuilder.CopyTo Метод

Определение

Перегрузки

CopyTo(Int32, Span<Char>, Int32)

Копирует символы из указанного сегмента этого экземпляра в конечный диапазон Char.

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

Копирует символы из указанного сегмента этого экземпляра в указанный массив Char.

CopyTo(Int32, Span<Char>, Int32)

Исходный код:
StringBuilder.cs
Исходный код:
StringBuilder.cs
Исходный код:
StringBuilder.cs

Копирует символы из указанного сегмента этого экземпляра в конечный диапазон Char.

public:
 void CopyTo(int sourceIndex, Span<char> destination, int count);
public void CopyTo (int sourceIndex, Span<char> destination, int count);
member this.CopyTo : int * Span<char> * int -> unit
Public Sub CopyTo (sourceIndex As Integer, destination As Span(Of Char), count As Integer)

Параметры

sourceIndex
Int32

Начальная позиция в этом экземпляре, откуда будут скопированы символы. Индексация начинается с нуля.

destination
Span<Char>

Доступный для записи диапазон, в который будут копироваться символы.

count
Int32

Число копируемых знаков.

Комментарии

Метод CopyTo предназначен для использования в редких случаях, когда необходимо эффективно копировать последовательные StringBuilder разделы объекта в диапазон.

Например, код может заполнить StringBuilder объект большим количеством символов, а затем использовать CopyTo метод для копирования небольших последовательных частей объекта в StringBuilder диапазон, в котором обрабатываются части. При обработке всех данных в объекте StringBuilder размер StringBuilder объекта устанавливается равным нулю и цикл повторяется.

Применяется к

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

Исходный код:
StringBuilder.cs
Исходный код:
StringBuilder.cs
Исходный код:
StringBuilder.cs

Копирует символы из указанного сегмента этого экземпляра в указанный массив Char.

public:
 void CopyTo(int sourceIndex, cli::array <char> ^ destination, int destinationIndex, int count);
public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count);
[System.Runtime.InteropServices.ComVisible(false)]
public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count);
member this.CopyTo : int * char[] * int * int -> unit
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.CopyTo : int * char[] * int * int -> unit
Public Sub CopyTo (sourceIndex As Integer, destination As Char(), destinationIndex As Integer, count As Integer)

Параметры

sourceIndex
Int32

Начальная позиция в этом экземпляре, откуда будут скопированы символы. Индексация начинается с нуля.

destination
Char[]

Массив, в который копируются символы.

destinationIndex
Int32

Начальная позиция в массиве destination, в которую копируются символы. Индексация начинается с нуля.

count
Int32

Число копируемых знаков.

Атрибуты

Исключения

destination имеет значение null.

Значение sourceIndex, destinationIndex или count меньше нуля.

-или-

sourceIndex больше длины этого экземпляра.

sourceIndex + count больше длины этого экземпляра.

-или-

Значение destinationIndex + count превышает длину destination.

Примеры

В следующем примере демонстрируется CopyTo метод.

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

using namespace System;
using namespace System::Text;

int main()
{
   array<Char>^dest = gcnew array<Char>(6);
   StringBuilder^ src = gcnew StringBuilder( "abcdefghijklmnopqrstuvwxyz!" );
   dest[ 1 ] = ')';
   dest[ 2 ] = ' ';

   // Copy the source to the destination in 9 pieces, 3 characters per piece.
   Console::WriteLine( "\nPiece) Data:" );
   for ( int ix = 0; ix < 9; ix++ )
   {
      dest[ 0 ] = ix.ToString()[ 0 ];
      src->CopyTo( ix * 3, dest, 3, 3 );
      Console::Write( "    " );
      Console::WriteLine( dest );
   }
}

/*
This example produces the following results:

Piece) Data:
    0) abc
    1) def
    2) ghi
    3) jkl
    4) mno
    5) pqr
    6) stu
    7) vwx
    8) yz!
*/
// This example demonstrates the CopyTo(Int32, Char[], Int32, Int32) method.

// Typically the destination array is small, preallocated, and global while
// the StringBuilder is large with programmatically defined data.
// However, for this example both the array and StringBuilder are small
// and the StringBuilder has predefined data.

using System;
using System.Text;

class Sample
{
    protected static char[] dest = new char[6];
    public static void Main()
    {
    StringBuilder src = new StringBuilder("abcdefghijklmnopqrstuvwxyz!");
    dest[1] = ')';
    dest[2] = ' ';

// Copy the source to the destination in 9 pieces, 3 characters per piece.

    Console.WriteLine("\nPiece) Data:");
    for(int ix = 0; ix < 9; ix++)
        {
        dest[0] = ix.ToString()[0];
        src.CopyTo(ix * 3, dest, 3, 3);
        Console.Write("    ");
        Console.WriteLine(dest);
        }
    }
}
/*
This example produces the following results:

Piece) Data:
    0) abc
    1) def
    2) ghi
    3) jkl
    4) mno
    5) pqr
    6) stu
    7) vwx
    8) yz!
*/
// This example demonstrates the CopyTo(Int32, Char[], Int32, Int32) method.

// Typically the destination array is small, preallocated, and global while
// the StringBuilder is large with programmatically defined data.
// However, for this example both the array and StringBuilder are small
// and the StringBuilder has predefined data.

open System.Text

let dest = Array.zeroCreate 6

let src = StringBuilder "abcdefghijklmnopqrstuvwxyz!"
dest[1] <- ')'
dest[2] <- ' '

// Copy the source to the destination in 9 pieces, 3 characters per piece.

printfn "\Piece) Data:"
for i = 0 to 8 do
    dest[0] <- (string i)[0]
    src.CopyTo(i * 3, dest, 3, 3)
    printfn $"    {dest}"

// This example produces the following results:
//       Piece) Data:
//           0) abc
//           1) def
//           2) ghi
//           3) jkl
//           4) mno
//           5) pqr
//           6) stu
//           7) vwx
//           8) yz!
' Typically the destination array is small, preallocated, and global while 
' the StringBuilder is large with programmatically defined data. 
' However, for this example both the array and StringBuilder are small 
' and the StringBuilder has predefined data.

Imports System.Text

Class Sample
   Protected Shared dest(5) As Char
   
   Public Shared Sub Main()
      Dim src As New StringBuilder("abcdefghijklmnopqrstuvwxyz!")
      dest(1) = ")"c
      dest(2) = " "c
      
      ' Copy the source to the destination in 9 pieces, 3 characters per piece.
      Console.WriteLine(vbCrLf & "Piece) Data:")
      Dim ix As Integer
      For ix = 0 To 8
         dest(0) = ix.ToString()(0)
         src.CopyTo(ix * 3, dest, 3, 3)
         Console.Write("    ")
         Console.WriteLine(dest)
      Next ix
   End Sub
End Class
'
' This example produces the following results:
'
' Piece) Data:
'     0) abc
'     1) def
'     2) ghi
'     3) jkl
'     4) mno
'     5) pqr
'     6) stu
'     7) vwx
'     8) yz!

Комментарии

Метод CopyTo предназначен для использования в редких случаях, когда необходимо эффективно копировать последовательные StringBuilder разделы объекта в массив. Массив должен быть фиксированным размером, предварительно выделяемым, пригодным для повторного использования и, возможно, глобально доступным.

Например, код может заполнить StringBuilder объект большим количеством символов, а затем использовать CopyTo метод для копирования небольших последовательных фрагментов объекта в StringBuilder массив, где обрабатываются части. При обработке всех данных в объекте StringBuilder размер StringBuilder объекта устанавливается равным нулю и цикл повторяется.

Применяется к