문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top