In C#, the CopyTo() is a method of String Class. It is used to copy a specified number of characters from a specified position in the string and it copies the characters of this string into an array of Unicode characters.
Example 1: Using the CopyTo() method to copy characters from a string to a character array.
// C# program to illustrate the
// String.CopyTo() Method
// Method
using System;
class Geeks
{
public static void Main()
{
// Creating a string
string s = "GeeksForGeeks";
// Destination char array
char[] dest = new char[3];
//Copying 3 characters from the 5th index
//of the string to the destination char array.
s.CopyTo(5, dest, 0, 3);
// Displaying the copied string
Console.WriteLine($"The Copied String is: {new string(dest)}");
}
}
Output
The Copied String is: For
Syntax of String CopyTo() Method
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
Parameters:
- sourceIndex: Index of String to be copied. Its type is System.Int32 .
- destination: It is the array of Unicode characters to which characters will be copied. Its type is System.Char[].
- destinationIndex: It is the the starting index of the array from where the copy operation begins. Its type is System.Int32.
- count: It is the number of characters which will copy to the destination. Its type is System.Int32.
Exceptions:
- ArgumentNullException: If the destination array is null then it will throw this Exception.
- ArgumentOutOfRangeException: There are different cases when an exception occurs
- If sourceIndex, destinationIndex, or count is negative.
- If sourceIndex does not identify a position in the current instance.
- If destinationIndex does not identify a valid index in the destination array.
- If the count is greater than the length of the substring from startIndex to the end of this instance
- If the count is greater than the length of the subarray from destinationIndex to the end of the destination array.
Example 2: Using the CopyTo() method to modify an existing character array.
// C# program to illustrate the
// ToCopy() string method
using System;
class Geeks
{
public static void Main()
{
string s = "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
s.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