C# String CopyTo()

The CopyTo() method in C# is used to copy a specified number of characters from a string to a character array. Here’s the syntax for the CopyTo() method:

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

Parameters:

  • sourceIndex: The index in the string where the copying starts.
  • destination: The character array where the copied characters will be placed.
  • destinationIndex: The starting index in the destination array where the characters will be copied.
  • count: The number of characters to be copied.

Example usage:

string sourceString = "Hello, world!";
char[] destinationArray = new char[5];

sourceString.CopyTo(7, destinationArray, 0, 5);

Console.WriteLine(destinationArray);  // Output: "world"

In this example, the CopyTo() method is called on the sourceString with sourceIndex set to 7, indicating that the copying should start from the character at index 7 (which is ‘w’ in the source string). The destinationArray is provided as the target array to store the copied characters, starting from index 0. The count is set to 5, specifying that five characters should be copied. The result is that the characters “world” are copied from the source string to the destination array. Finally, the destination array is printed to the console, resulting in the output “world”.

C# String CopyTo() Method Example:

Certainly! Here’s an example that demonstrates the usage of the CopyTo() method in C#:

string sourceString = "Hello, world!";
char[] destinationArray = new char[5];

sourceString.CopyTo(7, destinationArray, 0, 5);

Console.WriteLine(destinationArray);  // Output: "world"

In this example, we have a sourceString initialized with the value “Hello, world!”. We also declare a character array destinationArray with a length of 5.

The CopyTo() method is then called on the sourceString object. We pass the following arguments to the method:

  • sourceIndex: 7, indicating that the copying should start from the character at index 7 in the source string (which is the letter ‘w’).
  • destination: destinationArray, specifying the character array where the copied characters will be placed.
  • destinationIndex: 0, indicating that the copying should start from the beginning of the destination array.
  • count: 5, specifying that five characters should be copied.

After calling the CopyTo() method, the characters “world” are copied from the source string to the destination array. Finally, the content of the destinationArray is printed to the console, resulting in the output “world”.