954,170 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to append string in front

I have a string variable .. i need to append some value in front of this string ... i tried pad left function.. but it was not working

for example

string s= "sample"


now in want to insert "daniweb " , so my output of string s will be "daniweb sample"

raj416
Newbie Poster
14 posts since Jan 2008
Reputation Points: 12
Solved Threads: 2
 
Jx_Man
Nearly a Senior Poster
3,328 posts since Nov 2007
Reputation Points: 1,372
Solved Threads: 444
 

Or you could just go the easy route

string s= "sample";
s = "daniweb " + s;
dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Or you could just go the easy route

string s= "sample";
s = "daniweb " + s;

This is better, unless you do it often. Remeber each + used allocates and floats another copy of the string.

nvmobius
Light Poster
39 posts since Jul 2008
Reputation Points: 11
Solved Threads: 4
 

Correct nvmobius, I'll add if you are doing this with more than just a simple example like that, might want to try this.

StringBuilder sb = new StringBuilder();
  sb.Append("sample");
  sb.Insert(0, "daniweb ");
  string s = sb.ToString();
dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Correct nvmobius, I'll add if you are doing this with more than just a simple example like that, might want to try this.

StringBuilder sb = new StringBuilder();
  sb.Append("sample");
  sb.Insert(0, "daniweb ");
  string s = sb.ToString();

The downside of StringBuilder (and secretly String.Format) is that the allocation/release cost is several times that of the base String class. I'll see if I can find the MS developers' post, but if I remember correctly appending 3 strings together is cheaper than allocating, and using a StringBuilder to do the same thing. 4 strings is where StringBuilder becomes cheaper (total clock cycles, including garbage collector time).

nvmobius
Light Poster
39 posts since Jul 2008
Reputation Points: 11
Solved Threads: 4
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You