C# | CopyTo() Method
Last Updated :
31 Jan, 2019
In C#, CopyTo() method is a string method. 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 a array of Unicode characters.
Syntax:
public void CopyTo(int sourceIndex, char[] destination,
int destinationIndex, int count)
Explanation: CopyTo() method will copied the count characters from the sourceIndex position to the destinationIndex position of destination character array. This method accepts four parameters as follows :
- sourceIndex : Index of String to be copied. And 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 starting index of array from where the copy operation begins. Its type is System.Int32.
- count : It is the number of characters which will copy to destination. Its type is System.Int32.
Examples :
Input : str = "GeeksForGeeks"
char [] Copystring = new char[15];
str.CopyTo(5, Copystring, 0, 3);
Output: For
Input : str2 = "GeeksForGeeks";
char [] Copystring = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
str2.CopyTo(8, Copystring, 6, 5);
Output: Hello Geeks
Below example programs illustrate the ToCopy() Method :
- Example 1:
using System;
class Geeks {
public static void Main()
{
string str = "GeeksForGeeks" ;
char [] dest = new char [15];
str.CopyTo(5, dest, 0, 3);
Console.Write( "The Copied String in dest Variable is: " );
Console.WriteLine(dest);
}
}
|
Output:
The Copied String in dest Variable is: For
- Example 2:
using System;
class Geeks {
public static void Main()
{
string str2 = "GeeksForGeeks" ;
char [] dest = { 'H' , 'e' , 'l' , 'l' , 'o' , ' ' ,
'W' , 'o' , 'r' , 'l' , 'd' };
str2.CopyTo(8, dest, 6, 5);
Console.Write( "String Copied in dest is: " );
Console.WriteLine(dest);
}
}
|
Output:
String Copied in dest is: Hello Geeks
Note: If “destination” is null then it will cause an Exception as ArgumentNullException. There are different cases when exception occurs: ArgumentOutOfRangeException
cases 1: if sourceIndex, destinationIndex, or count is negative.
cases 2: if sourceIndex does not identify a position in the current instance.
cases 3: if destinationIndex does not identify a valid index in the destination array.
cases 4: if the count is greater than the length of the substring from startIndex to the end of this instance
cases 5: if the count is greater than the length of the subarray from destinationIndex to the end of the destination array.
Reference: https://msdn.microsoft.com/en-us/library/system.string.copyto
Share your thoughts in the comments
Please Login to comment...