1

Is there a (system library) way to insert a formatted string to a StringBuilder that will be identical to the following?

myStringBuilder.Insert(0, string.Format("%02X", someInt)); 

I haven't find any in the class documentation.

6
  • as i know this will work propertly Commented Sep 20, 2011 at 7:35
  • @Jon - I was just wondering if there's a library support for that, or should I write as I did. Commented Sep 20, 2011 at 7:36
  • But obviously you do have access to the internet and MSDN online, msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx. There is no InsertFormat method. Commented Sep 20, 2011 at 7:36
  • @Pranay Rana - thanks, I know, I meant something like AppendFormat Commented Sep 20, 2011 at 7:37
  • @Jodrell - That's a fair comment, yet I thought I might be missing something. Commented Sep 20, 2011 at 7:38

2 Answers 2

3

You can create an extension method

public static StringBuilder InsertFormat(this StringBuilder sb, string format, params object[] args)
{
    sb.Insert(0, string.Format(format, args)); 
}

Then you can write

myStringBuilder.InsertFormat("%02X", someInt); 
Sign up to request clarification or add additional context in comments.

2 Comments

This solution is not a system library method
Well that's what I currently do pretty much. I wondered if there is a library method though. Thanks!
1

StringBuilder provides you the method AppendFormat which does the append and the format in one call but adds the content in the end of the buffer.

In your specific case since there is no provided .NET framework method which does InsertFormat as you wish you either use the method shown above in your question or create an extension method (for example call it InsertFormat) and then use it in your project.

4 Comments

The extension method is probably the best suggestion here, but I feel this is technically not a good answer because the question specifically stipulates "system library method".
@Jodrell - No is a legit answer :). BTW why append seems more efficient to you?
@MByd, internally the string array is some buffer of chars, when you Append the new chars are written to the end (if there is not enough space the buffer is extended.) When you Insert, a space is made by shifting all the "after" chars up the buffer and the new chars go in the gap. It is possible that the implementation could be some sort of linked list but that sounds too ineffiecient, in general, to be true and I believe that I've read that that is no the case.
further to previous comment stackoverflow.com/questions/6524240/how-does-stringbuilder-work, note the last post 1024strongoxen.blogspot.com/2010/02/… which suggests it may actually be a linked list now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.