C# `String.CopyTo()`: Efficiently Copying String Segments to Character Arrays

Learn how to use C#'s `String.CopyTo()` method to efficiently copy portions of a string into a character array. This tutorial explains the method's parameters, demonstrates its usage with code examples, and highlights its applications in string manipulation and data extraction tasks.



Understanding C#'s `CopyTo()` Method for Strings

The C# `CopyTo()` method for strings allows you to copy a portion of a string into a character array. This provides a way to extract specific segments of a string for further processing or manipulation.

`CopyTo()` Method Signature


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

The method takes four parameters:

  • sourceIndex (int): The starting index within the source string from where copying begins (zero-based).
  • destination (char[]): The character array to copy the characters into.
  • destinationIndex (int): The starting index within the destination array where copying begins (zero-based).
  • count (int): The number of characters to copy.

Example


using System;

public class StringExample {
    public static void Main(string[] args) {
        string str = "Hello C#, How Are You?";
        char[] charArray = new char[15];
        str.CopyTo(10, charArray, 0, 12); // Copies 12 characters starting at index 10
        Console.WriteLine(charArray); // Output: How Are You?
    }
}

This example copies 12 characters from the string "Hello C#, How Are You?" (starting at index 10) into a character array. The resulting character array contains "How Are You?".