Copy a String in C#

In this article we will discuss about how to copy a string in to another string
  • 3834

The string class provides two methods to copy strings – Copy and CopyTo.
The Copy method copies the contents of a string to another. The Copy method is a static method and takes a string as input and returns another string with the same contents as the input string. For example, the following code copies authorName string to copyAuthor string.

 

string firstName = "Mahesh";
string lastName = "Chand";
string authorName = firstName + " " + lastName;
Console.WriteLine("Original String: {0}", authorName);
string copyAuthor = string.Copy(authorName);
Console.WriteLine("Copied String: {0}", copyAuthor);


The CopyTo method copies a specified number of characters from a specified position in this instance to a specified position in an array of characters. For example, the following example copies contents of str1 to an array of characters. You can also specify the starting character of a string and the number of characters you want to copy to the array.

string firstName = "Mahesh";
string lastName = "Chand";

string authorName = firstName + " " + lastName;

char[] copiedString = { 'n', 'e', 'e', 'l', ' ', 'b', 'e', 'n', 'i', 'w', 'l' };

Console.WriteLine("Original String: {0}", authorName);

authorName.CopyTo(2, copiedString, 2, 6);

Console.WriteLine(copiedString);
 
Further Readings
 
You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.