sprintf() はそれを行うことができます:
sprintf(test1.name,"%-15s","John Doe");
printf("[%s] length of test1.name: %ld\n",test1.name,strlen(test1.name));
sprintf(test1.name,"%-*s",(int) sizeof(test1.name) - 1,"Jane Jones");
printf("[%s] length of test1.name: %ld\n",test1.name,strlen(test1.name))
出力:
[John Doe ] length of test1.name: 15
[Jane Jones ] length of test1.name: 15
また
#include <stdio.h>
#include <string.h>
int copy_with_pad(char *destination,const char *source, int dest_size, char pad_char)
{
int pad_ctr = 0;
if (dest_size < 1 ) return -1;
int source_length = strlen(source);
int data_size = dest_size - 1;
destination[data_size] = '\0';
int i = 0;
while (i < data_size)
{
if ( i >= source_length )
{
destination[i] = pad_char;
pad_ctr++;
}
else
destination[i] = source[i];
i++;
}
return pad_ctr;
}
int main(void)
{
struct test {
char name[16];
};
struct test test1;
int chars_padded = copy_with_pad(test1.name,"Hollywood Dan",
sizeof(test1.name),' ');
printf("%d padding chars added: [%s]\n",chars_padded,test1.name);
chars_padded = copy_with_pad(test1.name,"The Honorable Hollywood Dan Jr.",
sizeof(test1.name),' ');
printf("%d padding chars added: [%s]\n",chars_padded,test1.name);
chars_padded = copy_with_pad(test1.name,"",16,' ');
printf("%d padding chars added: [%s]\n",chars_padded,test1.name);
}
出力
2 padding chars added: [Hollywood Dan ]
0 padding chars added: [The Honorable H]
15 padding chars added: [ ]