Open In App

StringBuilder.CopyTo Method in C#

This method is used to copy the characters from a specified segment of this instance to a specified segment of a destination Char array.

Syntax:



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

Parameters:



Exceptions:

Example 1:




// C# program to illustrate the
// CopyTo () StringBuilder Method
using System;
using System.Text;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("GeeksForGeeks");
  
        char[] dest = new char[15];
  
        // str index 5 to 5+3 has to
        // copy into Copystring
        // 3 is no. of character
        // 0 is start index of Copystring
        str.CopyTo(5, dest, 0, 3);
  
        // Displaying String
        Console.Write("The Copied String in "+
                        "dest Variable is: ");
        Console.WriteLine(dest);
    }
}

Output:
The Copied String in dest Variable is: For

Example 2:




// C# program to illustrate the
// CopyTo() StringBuilder Method
using System;
using System.Text;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str2
            = new StringBuilder("GeeksForGeeks");
  
        char[] dest = { 'H', 'e', 'l', 'l', 'o', ' ',
                           'W', 'o', 'r', 'l', 'd' };
  
        // str index 8 to 8 + 5 has
        // to copy into Copystring
        // 5 is no of character
        // 6 is start index of Copystring
        str2.CopyTo(8, dest, 6, 5);
  
        // Displaying the result
        Console.Write("String Copied in dest is: ");
        Console.WriteLine(dest);
    }
}

Output:
String Copied in dest is: Hello Geeks

Reference:


Article Tags :
C#