C# String CopyTo Method Example

In this source code example, we will demonstrate the usage of String.CopyTo() method in C# with an example.

The C# String.CopyTo() method is used to copy a specified number of characters from the specified position in the string. It copies the characters of this string into a char array.

C# String CopyTo Method Example

The following example demonstrates the CopyTo method.
using System;

public class StringDemo
{
    public static void Main(string[] args)
    {
       // Embed an array of characters in a string
        string strSource = "changed";
        char [] destination = { 'T', 'h', 'e', ' ', 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ',
                'a', 'r', 'r', 'a', 'y' };

        // Print the char array
        Console.WriteLine( destination );

        // Embed the source string in the destination string
        strSource.CopyTo ( 0, destination, 4, strSource.Length );

        // Print the resulting array
        Console.WriteLine( destination );

        strSource = "A different string";

        // Embed only a section of the source string in the destination
        strSource.CopyTo ( 2, destination, 3, 9 );

        // Print the resulting array
        Console.WriteLine( destination ); 

    }

}

Output:

The initial array
The changed array
Thedifferentarray

Related C# String Examples

References



Comments