将C++的sprintf格式字符串翻译成C#的string.Format

the*_*kup 5 c# c++ string.format printf

我找到了以下C++代码(评论自己添加):

// 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());
Run Code Online (Sandbox Code Playgroud)

然后我尝试将其翻译为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]);
Run Code Online (Sandbox Code Playgroud)

基本上,C++格式字符串"%s_%0*s.bmp"的C#等价物是什么?

编辑,@ Mark Byers:

我已经尝试了你的代码并做了一个小测试程序:

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();
 }
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它不是填充.

编辑:搞定了; 如果n = 2,则不会填充.

Mar*_*ers 3

要用零填充字符串,请使用string.PadLeft

frames[k].PadLeft(n, '0')
Run Code Online (Sandbox Code Playgroud)

结合string.Format

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

请注意,我已更改kn,因为我认为这是原始代码中的错误。我认为文件名上的填充长度不太可能在循环的每次迭代中增加一。