This method is used to copy the characters from a specified segment of this instance to a specified segment of a destination Char array.
Syntax:
public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count);
Parameters:
- sourceIndex: It is the starting position in this instance where characters will be copied from. The index is zero-based.
- destination: It is the array where characters will be copied.
- destinationIndex: It is the starting position in destination where characters will be copied. The index is zero-based.
- count: It is the number of characters to be copied.
Exceptions:
- ArgumentNullException: If the destination is null.
- ArgumentOutOfRangeException: If the sourceIndex, destinationIndex, or count, is less than zero or the sourceIndex is greater than the length of this instance.
- ArgumentException: If the sourceIndex + count is greater than the length of this instance or the destinationIndex + count is greater than the length of destination.
Example 1:
// C# program to illustrate the // CopyTo () StringBuilder Method using System;
using System.Text;
class Geeks {
// Main Method
public static void Main()
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str
= new StringBuilder( "GeeksForGeeks" );
char [] dest = new char [15];
// str index 5 to 5+3 has to
// copy into Copystring
// 3 is no. of character
// 0 is start index of Copystring
str.CopyTo(5, dest, 0, 3);
// Displaying String
Console.Write( "The Copied String in " +
"dest Variable is: " );
Console.WriteLine(dest);
}
} |
Output:
The Copied String in dest Variable is: For
Example 2:
// C# program to illustrate the // CopyTo() StringBuilder Method using System;
using System.Text;
class Geeks {
// Main Method
public static void Main()
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str2
= new StringBuilder( "GeeksForGeeks" );
char [] dest = { 'H' , 'e' , 'l' , 'l' , 'o' , ' ' ,
'W' , 'o' , 'r' , 'l' , 'd' };
// str index 8 to 8 + 5 has
// to copy into Copystring
// 5 is no of character
// 6 is start index of Copystring
str2.CopyTo(8, dest, 6, 5);
// Displaying the result
Console.Write( "String Copied in dest is: " );
Console.WriteLine(dest);
}
} |
Output:
String Copied in dest is: Hello Geeks
Reference:
- https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.copyto?view=netframework-4.7.2