views:

119

answers:

4

What is C# analog of C snprintf()?

In C code here we use

 snprintf(buf, sizeof(buf), outfilename, frame);

What could be its exact analog?

+2  A: 

StringBuilder.AppendFormat String.Format is the closest. It performs the same operation, but do note that the format strings are in a different format.

Using String.Format:

string buf = string.Format("{0}", frame);

Using StringBuilder.AppendFormat:

StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}", frame);
280Z28
+2  A: 

The most basic version is String.Format.

string result = String.Format(format, arg0, arg1, ..., argn);

But many other classes support something similar, including all classes that derive from TextWriter. There are some examples in this question Which methods in the 3.5 framework have a String.Format-like signature?

  • Console.Write
  • StreamWriter.Write
  • StringWriter.Write
  • StringBuilder.AppendFormat
  • many more...
Mark Byers
A: 

If you're assigning to a string, use String.Format

var newString = String.Format("Number: {0}", 10);

If you're looking to append a ton of strings, use the StringBuilder.AppendFormat. It'll save you in the long run because they can be chained, saving space.

var result = new StringBuilder().AppendFormat("{0}", 10).AppendFormat("{0}", 11).ToString();
DarkBobG
A: 

What could be its exact analog?

There is no exact analog, because:

  1. strings in C and C# are implemented differently. In C, strings are mutable arrays of chars, while in .NET they are immutable object instances. So in .NET you don't "write to a buffer" as snprintf does, you just create an entire new string

  2. the format strings used in .NET (in String.Format, Console.WriteLine, etc) are very different from C (different placeholder format)

As mentioned in other answers, the closest equivalent is String.Format, but it's definitely not an exact analog

Thomas Levesque