📜  C#| CopyTo()方法

📅  最后修改于: 2021-05-29 23:18:14             🧑  作者: Mango

C#中,CopyTo()方法是一个字符串方法。它是用来指定的字符数的指定位置的字符串中复制并将其复制这个字符串的字符转换成Unicode字符阵列。

句法:

public void CopyTo(int sourceIndex, char[] destination, 
                      int destinationIndex, int count)

说明: CopyTo()方法会将计数字符从sourceIndex位置复制到目标字符数组的destinationIndex位置。此方法接受四个参数,如下所示:

  1. sourceIndex:要复制的字符串的索引。它的类型是System.Int32
  2. destination:这是将字符复制到的Unicode字符数组。它的类型是System.Char []
  3. destinationIndex:它是复制操作从其开始的数组的起始索引。它的类型是System.Int32
  4. 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

参考: https : //msdn.microsoft.com/en-us/library/system。字符串.copyto