views:

397

answers:

2

I found the following C++ code (comments added myself):

// frame_name is a char array
// prefix is std::string
// k is a for loop counter
// frames is a std::vector string
sprintf(frameName, "%s_%0*s.bmp", prefix.c_str(), k, frames[k].c_str());

I then try to translate it to C#

// prefix is string
// k is a for loop counter
// frames is List<string>
string frameName = string.Format("{0}_(what goes in here?).bmp", prefix, k, frames[k]);

Basically, what would be the C# equivalent of the C++ format string "%s_%0*s.bmp"?

Edit, @Mark Byers:

I've tried your code and made a little test program:

static void Main(string[] args)
{
    List<string> frames = new List<string>();
    frames.Add("blah");
    frames.Add("cool");
    frames.Add("fsdt");

    string prefix = "prefix";
    int n = 2;
    int k = 0;
    string frameName = string.Format("{0}_{1}.bmp", prefix, frames[k].PadLeft(n, '0'));
    Console.WriteLine(frameName); // outputs prefix_blah.bmp, should output prefix_00blah.bmp
    Console.ReadLine();
 }

It's not padding for some reason.

Edit: Got it working; won't pad if n = 2.

+1  A: 

For formatting details like the 0* in %0*s, I'd do it this way:

string.Format("{0}_{1}.bmp", prefix, frames[k].PadLeft(k,'0'));

If I have it right, it will take frames[k], and left-pad it with 0's.

e.g.:

k=10;
frames[k] = "Hello";
frames[k].PadLeft(k,'0') ==> "00000Hello";

Is that what you're after?

abelenky
The * in `%0*s` requests that a parameter be used to specify the precision. Thus, 1 for `%s`, 1 for the `*`, and 1 for the `%0*s`, or 3.
Thanatos
Thanks for the update, @Thantos. Editing answer.
abelenky
Except `0` with `s` would appear to be UB - see my comment on the question.
Thanatos
Thanks, going to test out the code; I'll let you know how it turns out.
thebackup
+3  A: 

To pad a string with zeros use string.PadLeft:

frames[k].PadLeft(n, '0')

In combination with string.Format:

int n = 15; // Get this from somewhere.
string frameName = string.Format("{0}_{1}.bmp",
                                 prefix,
                                 frames[k].PadLeft(n, '0'));

Note that I have changed k to n, as I assume that this is a bug in the original code. I think it's unlikely that the length of the padding on the file name was meant to increase by one in each iteration of the loop.

Mark Byers
Thanks, but apparently it's not padding; see original post.
thebackup
@thebackup: It's not padding because you've set n = 2. n is the minimum length. If you just want to add two zeros always that is much easier and doesn't need the PadLeft function.
Mark Byers
Oh okay, I get it now; it works as expected - it's just what I wanted in the first place. Thanks very much, Mark.
thebackup