Domanda

Ho trovato il seguente codice C ++ (commenti me aggiunto):

// 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());

Allora provo a tradurre in 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]);

In sostanza, quale sarebbe il C # equivalente del ++ stringa di formato "% s_% 0 * s.bmp"?

C

Modifica, @ Mark Byers:

Ho provato il codice e ha fatto un po 'di programma di test:

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();
 }

Non è imbottitura per qualche ragione.

Modifica: ottenuto che funziona; non sarà pad se n = 2.

È stato utile?

Soluzione

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.

Altri suggerimenti

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?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top