C# String CopyTo() Method


The CopyTo() method in C# is used to copy a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.

Syntax

public void CopyTo (int srcIndex, char[] dest, int desIndex, int count);

Above,

  • srcIndex − Index of the first character in this instance to copy.
  • dest − Array of Unicode characters to which characters in this instance are copied.
  • destIndex − The index in destination at which the copy operation begins.
  • Count − Number of characters in this instance to copy to destination.

Example

Let us now see an example -

 Live Demo

using System;
public class Demo {
   public static void Main() {
      string str = "JohnAndJacob";
      Console.WriteLine("String = "+str);
      char[] destArr = new char[20];
      str.CopyTo(1, destArr, 0, 4);
      Console.Write(destArr);
   }
}

Output

String = JohnAndJacob
ohnA

Example

Let us now see another example -

 Live Demo

using System;
public class Demo {
   public static void Main() {
      string str = "JohnAndJacob";
      Console.WriteLine("String = "+str);
      char[] destArr = new char[20];
      destArr[0] = 'A';
      destArr[1] = 'B';
      destArr[2] = 'C';
      destArr[3] = 'D';
      Console.WriteLine(destArr);
      str.CopyTo(2, destArr, 3, 4);
      Console.Write(destArr);
   }
}

Output

This will produce the following output -

String = JohnAndJacob
ABCD
ABChnAn

Updated on: 30-Apr-2020

993 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements