C# String - CopyTo() Method



The C# String CopyTo() method copies the text from the current string into a designated space (called a "span"). It can also take a certain number of characters starting from a specific position in the string and copy them to a particular position in an array of Unicode characters (a way of representing text).

Syntax

Following are the syntax of the C# string CopyTo() method −

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

Parameters

This method accepts the following parameters −

  • sourceIndex: It represents the index of the first character in this instance to copy.
  • destination: An array of Unicode characters to which characters in this instance are copied.
  • destinationIndex: It represents an index at which copy operation start.
  • count: The number of character to be copied to the destination in this instance.

Return value

This method does not return any value.

Example 1: Using the Overloaded Syntax of CopyTo

In this example, we use the CopyTo() method to copy the source string into the destination array. The source starts from the 0-index and starts copying from index 0 to the length of the source array in the destination array −

using System;
class Program {
   public static void Main() {
      string source = "Hello tutorialspoint!";
      char[] dest = new char[40];
	  
      // Use the CopyTo method
      source.CopyTo(0, dest, 0, source.Length);
      Console.WriteLine(new string(dest));
   }
}

Output

Following is the output −

Hello tutorialspoint!

Example 2: Copy 5 Characters Starting From Index 7

In this example, we use the CopyTo() method to copy 5 characters starting from index 7 in the source string to index 0 in the destination array −

using System;
class Program {
   static void Main() ;{
      string source = "Hello, World!";
      char[] destination = new char[20];

      source.CopyTo(7, destination, 0, 5);

      Console.WriteLine(new string(destination));
   }
}

Output

Following is the output −

World
csharp_strings.htm
Advertisements