StringBuilder.CopyTo() Method in C#


The StringBuilder.CopyTo() method in C# is used to copy the characters from a specified segment of this instance to a specified segment of a destination Char array.

Syntax

The syntax is as follows -

public void CopyTo (int sourceIndex, char[] dest, int destIndex, int count);

Above, the parameter sourceIndex is the starting position in this instance where characters will be copied from. The dest is the array where characters will be copied, whereas the destIndex is the starting position in destination where characters will be copied. The count parameter is the number of characters to be copied.

Example

Let us now see an example -

 Live Demo

using System;
using System.Text;
public class Demo {
   public static void Main() {
      StringBuilder strBuilder = new StringBuilder("ghgh78hkjj");
      char c = strBuilder[3];
      Console.WriteLine("String = "+strBuilder);
      Console.WriteLine("Character = "+c);
      char[] arr = new char[15];
      strBuilder.CopyTo(3, arr, 2, 6);
      Console.WriteLine("\nCopied String in char array...");
      Console.WriteLine(arr);
   }
}

Output

String = ghgh78hkjj
Character = h
Copied String in char array...
h78hkj

Example

Let us now see another example -

 Live Demo

using System;
using System.Text;
public class Demo {
   public static void Main() {
      StringBuilder strBuilder = new StringBuilder("JohnWick");
      Console.WriteLine("String = "+strBuilder);
      char[] arr = new char[5] {'a', 'b', 'c', 'd', 'e'};
      strBuilder.CopyTo(1, arr, 1, 3);
      Console.WriteLine("\nCopied String in char array...");
      Console.WriteLine(arr);
   }
}

Output

This will produce the following output -

String = JohnWick
Copied String in char array...
aohne
raja
Published on 03-Dec-2019 13:08:45
Advertisements