String.CopyTo() method with example in C#

C# String.CopyTo() technique: Here, we will find out about the CopyTo() strategy for String class with example.

C# String.CopyTo() Method

String.CopyTo() technique is utilized to duplicate a predetermined number of characters from given files of the string to the predefined position in a character cluster.

Syntax:

    public void CopyTo (int source_index, 
        char[] destination, 
        int destination_index, 
        int count);

Parameter:

  • source_index – record to the string from where you need to duplicate the string
  • goal – target character cluster in which you need to duplicate the piece of the string
  • destination_index – a record in the focused on character cluster
  • tally – complete number of characters to be duplicated in character cluster
  • Return value: void – It returns nothing.

Example:

    Input:
    string str = "Hello world!";
    char[] arr = { 'I', 'n', 'c', 'l', 'u', 'd', 'H', 'e', 'l', 'p' };
    
    copying "Hello " to arr:
    str.CopyTo(0, arr, 0, 6);

    Output:
    str = Hello world!
    arr = Hello Just

C# Example to duplicate characters from string to characters exhibit utilizing String.CopyTo() strategy:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void printCharArray(char[] a){
            foreach (char item in a)
            {
                Console.Write(item);
            }
        }

        static void Main(string[] args)
        {
            string str = "Hello world!";
            char[] arr = { 'I', 'n', 'c', 'l', 'u', 'd', 'H', 'e', 'l', 'p' };

            //printing values
            Console.WriteLine("Before CopyTo...");
            Console.WriteLine("str = " + str);
            Console.Write("arr = ");
            printCharArray(arr);
            Console.WriteLine();

            //copying "Hello " to arr
            str.CopyTo(0, arr, 0, 6);

            //printing values
            Console.WriteLine("After CopyTo 1)...");
            Console.WriteLine("str = " + str);
            Console.Write("arr = ");
            printCharArray(arr);
            Console.WriteLine();


            //copying "World! " to arr
            str.CopyTo(6, arr, 0, 6);

            //printing values
            Console.WriteLine("After CopyTo 1)...");
            Console.WriteLine("str = " + str);
            Console.Write("arr = ");
            printCharArray(arr);
            Console.WriteLine();

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output:

Before CopyTo...
str = Hello world!
arr = JustTechReview
After CopyTo 1)...
str = Hello world!
arr = Hello Just
After CopyTo 1)...
str = Hello world!
arr = world!Just

Leave a Comment

error: Alert: Content is protected!!