Copy And Concatenate String In C#

Copy and Concatenating Strings

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

The following source code concatenates two strings.
  1. string str1 = "ppp";  
  2. string str2 = "ccc";  
  3. string strRes = String.Concat(str1, str2);  
  4. Console.WriteLine(strRes);   
The following source code concatenates one string and one object.
  1. object obj = (object)12;  
  2. strRes = String.Concat(str1, obj);  
  3. Console.WriteLine(strRes);  
The Copy 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.
  1. string str1 = "ppp";  
  2. string str2 = "ccc";  
  3. string strRes = String.Copy(str1);  
  4. Console.WriteLine("Copy result :" + strRes);  
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 number of characters you want to copy to the array.
  1. string str1 = "ppp";  
  2. char[] chrs = new Char[2];  
  3. 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.
  1. string str1 = "ppp";  
  2. object objClone = str1.Clone();  
  3. Console.WriteLine("Clone :"+objClone.ToString());  
The Join 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.
  1. string str1 = "ppp";  
  2. string str2 = "ccc";  
  3. string str3 = "kkk";  
  4. string[] allStr = new String[]{str1, str2, str3};  
  5. string strRes = String.Join(", ", allStr);  
  6. Console.WriteLine("Join Results: "+ strRes); 
The output from above codes is shown in below figure
c# string concat

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.