TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# CopyTo String Method

This C# example uses the CopyTo method on the string type. CopyTo copies a range of characters.

CopyTo takes string characters and puts them into an array.

It copies a group of characters from one source string into a character array of a certain size. This .NET Framework method provides optimized low-level code.

Example. To start, the CopyTo method on the string type must be called on an instance of a string object. String objects in the C# language can be represented by string literals, meaning "Literal".CopyTo() would be useful as well.

String Literal

Note: In this example, please notice how the char[] variable is allocated before CopyTo is invoked.

Char Array

Based on:

.NET 4.5

C# program that uses CopyTo

using System;

class Program
{
    static void Main()
    {
	// Declare a string constant and an output array.
	string value1 = "Dot Net Perls";
	char[] array1 = new char[3];
	// Copy the fifth, sixth, and seventh characters to the array.
	value1.CopyTo(4, array1, 0, 3);
	// Output the array we copied to.
	Console.WriteLine("--- Destination array ---");
	Console.WriteLine(array1.Length);
	Console.WriteLine(array1);
    }
}

Output

--- Destination array ---
3
Net

In this example, calling the CopyTo method is a void method call. The CopyTo method returns no reference to the copied data. The char array in the program instead has its characters changed internally in CopyTo.

Note: Arrays are indexed by their offsets. The fourth character where the CopyTo method begins copying is the letter "N".

Then: That character and the two following characters are copied into the char[] buffer and the buffer's values are printed to the screen.

Console.WriteLine

Internals. In the .NET Framework, the CopyTo instance method on string is contained in an unsafe context, meaning it can access pointers directly. However, using CopyTo is very reliable because it has been extensively tested.

Note: You do not need to enable the unsafe context to call CopyTo. The unsafe code is not your responsibility.

The CopyTo method internally calls into wstrcpy, which is a heavily optimized and unrolled loop. It copies characters quickly. Using CopyTo (or ToCharArray) is likely much faster than custom methods when the functionality is required.

ToCharArray

Substring. In most .NET programs, the CopyTo method is not necessary. Instead, your programs will often use Substring to copy one range of characters to another. But the CopyTo method along with ToCharArray can be used as optimizations.

Substring

Tip: CopyTo can help when interoperating with other programs and libraries that require character arrays.

Benchmark. Due to extreme boredom, I wanted to know whether using CopyTo is faster than a for-loop on a short string. I found that the for-loop is faster. This of course depends on your system and other factors.

And: For longer strings, the benchmark would need to be adjusted. Careful testing is needed.

C# program that benchmarks CopyTo, for-loop

using System;
using System.Diagnostics;

class Program
{
    const int _max = 100000000;
    static void Main()
    {
	char[] values = new char[100];

	var s1 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    "1234".CopyTo(0, values, 0, 4); // [CopyTo]
	}
	s1.Stop();
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    for (int j = 0; j < "1234".Length; j++) // [For-loop]
	    {
		values[j] = "1234"[j];
	    }
	}
	s2.Stop();
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));
	Console.Read();
    }
}

Output

11.44 ns, CopyTo
 8.64 ns, For-loop

Summary. We looked at the CopyTo method on the string type in the C# language targeting the .NET Framework. This method allows you to copy ranges of characters from a source string into target arrays.

Arrays

Review: CopyTo is a range-based ToCharArray method. It acts only for some characters in a range.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf