Thursday, 6 December 2012

String Concatenation in C#

String Concatenation in C#

Strings are immutable, so once it is created you cannot alter the content.

i.e String str="Hello";
     str[0]="G";   //will give compiler error.


String concatenations

Example 1
String str ="Hello";
  str = str+"World!";  
 //ouput HelloWorld!
//here new string object will be created, //previous reference will be released.

Example 2
---------------
   String str="Hello";
   String  nullStr=null;
   String  emptyStr=String.Empty;

Concatinating String with null values gives String

str = str+nullStr; //output: Hello


Concatinating String with Empty values gives String

str = str + emptyStr; //output: Hello

Example 3

Concatenating/joining multiple strings into single string using String.Concat


String strcat= String.Concat("Hello", "are ", " there?", " Where ", " are ", " u ", "going?");
Console.WriteLine(strcat);

Example 4


Concatenating/joining array values into single string using String.Concat   


String []strArr= new String[]{"Hello"," Are "," you "," there?"};

String strcat = String.Concat(strArr);  
//Output: Hello Are you there?

Add Integer/Single/Double to String 
String str2="Adding numbers to String";

str2 = str2 + 1;
           Console.WriteLine(str2);
           str2 = str2 + 1.1f;
           Console.WriteLine(str2);
           str2 = str2 + 2.0M;
           Console.WriteLine(str2);
           str2 = str2 + 2.2D;
           Console.WriteLine(str2);

/in above case no need of method  .ToString() to add int,single,double to string. Implicitely converted to String.


Concatenating
 String  with DateTime(Implicit conversion).

String str = "Time now is ";

str = str+DateTime.Now;

//output:
Time now is
 12/6/2014 11:40:19 AM





No comments:

Post a Comment