ARTICLE

Copy and Concatenate String in C#

Posted by Mahesh Chand Articles | String in C# August 21, 2010
This code snippet shows how to copy and concatenate strings in C#.
Reader Level:

Copy and Concatenating Strings

TheConcat method adds strings (or objects) and returns a new string. UsingConcat method, you can add two strings, two objects and one string and one object or more combination of these two.

The following source code concatenate two strings.

string str1 = "ppp";
string str2 = "ccc";
string strRes = String.Concat(str1, str2);
Console.WriteLine(strRes);

The following source code concatenates one string and one object.

object obj = (object)12;
strRes = String.Concat(str1, obj);
Console.WriteLine(strRes);

TheCopy method copies contents of a string to another. The Copy method takes a string as input and returns another string with the same contents as the input string. For example, the following code copies str1 to strRes.

string str1 = "ppp";
string str2 = "ccc";
string strRes = String.Copy(str1);
Console.WriteLine("Copy result :" + strRes);

TheCopyTo 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 number of characters you want to copy to the array.

string str1 = "ppp";
char[] chrs = new Char[2];
str1.CopyTo(0, chrs, 0, 2);

The Clone method returns a new copy of a string in form of object. The following code creates a clone of str1.

string str1 = "ppp";
object objClone = str1.Clone();
Console.WriteLine("Clone :"+objClone.ToString());

TheJoin method is useful when you need to insert a separator (String) between each element of a string array, yielding a single concatenated string. For example, the following sample inserts a comma and space (", ") between each element of an array of strings.

string str1 = "ppp";
string str2 = "ccc";
string str3 = "kkk";
string[] allStr = new String[]{str1, str2, str3};
string strRes = String.Join(", ", allStr);
Console.WriteLine("Join Results: "+ strRes);



Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.