在C#中,CopyTo()方法是一个字符串方法。它是用来指定的字符数的指定位置的字符串中复制并将其复制这个字符串的字符转换成Unicode字符阵列。
句法:
public void CopyTo(int sourceIndex, char[] destination,
int destinationIndex, int count)
说明: CopyTo()方法会将计数字符从sourceIndex位置复制到目标字符数组的destinationIndex位置。此方法接受四个参数,如下所示:
- sourceIndex:要复制的字符串的索引。它的类型是System.Int32 。
- destination:这是将字符复制到的Unicode字符数组。它的类型是System.Char [] 。
- destinationIndex:它是复制操作从其开始的数组的起始索引。它的类型是System.Int32 。
- count:这是将复制到目标位置的字符数。它的类型是System.Int32 。
例子 :
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
下面的示例程序说明了ToCopy()方法:
- 范例1:
// C# program to illustrate the // ToCopy() string method using System; class Geeks { // Main Method public static void Main() { string str = "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); } }
输出:The Copied String in dest Variable is: For
- 范例2:
// C# program to illustrate the // ToCopy() string method using System; class Geeks { // Main Method public static void Main() { string str2 = "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); } }
输出:String Copied in dest is: Hello Geeks
注意:如果“ destination”为null,则它将导致异常,如ArgumentNullException 。发生异常时有不同的情况: 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.
参考: https : //msdn.microsoft.com/en-us/library/system。字符串.copyto