C# String.CopyTo() Method with Example

In this tutorial, we will learn about the String.CopyTo() method with its usage, syntax, and examples. By IncludeHelp Last updated : April 07, 2023

C# String.CopyTo() Method

The String.CopyTo() method is used to copy a specified number of characters from given indexes of the string to the specified position in a character array.

Syntax

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

Parameter(s)

  • source_index - index to the string from where you want to copy the string
  • destination - target character array in which you want to copy the part of the string
  • destination_index - index in the targeted character array
  • count - total number of characters to be copied in character array

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 Help

C# example to copy a characters from string to characters array using String.CopyTo() method

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 = IncludHelp
After CopyTo 1)...
str = Hello world!
arr = Hello Help
After CopyTo 1)...
str = Hello world!
arr = world!Help

Reference: String.CopyTo(Int32, Char[], Int32, Int32) Method




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.