Sunday, May 6, 2012

How to Insert text to string

In this article we will speak about inserting text to the string.

Task:
You have some  string (for example "please" ) and want to insert in into specific location of other string which is already exist string.
Here is the code:
string str1="Please";
string str2= "give me a pen,";
str2=  str2 .Insert(14, str1);
Console.WriteLine( str2 );

The result will be "give me a pen,Please"
Inserting char value is a little different, you need to StringBuilder.
Here is the code:
char char1 = 'P';
StringBuilder srt1 = new StringBuilder(" give me a pen, ");
sourceString.Insert (14,  char1  );
Console.WriteLine( srt1  );
 The result will be "give me a pen,P"
You also can learn more about Sting Insert method in MSDN documention.