I want to add a variable number of spaces to a string in C, and wanted to know if there is a standard way to do it, before I implement it by myself.
Until now I used some ugly ways to do it:
This is one way I used:
add_spaces(char *dest, int num_of_spaces) {
int i;
for (i = 0 ; i < num_of_spaces ; i++) {
strcat(dest, " ");
}
}
This one is a better in performance, but also doesn't look standard:
add_spaces(char *dest, int num_of_spaces) {
int i;
int len = strlen(dest);
for (i = 0 ; i < num_of_spaces ; i++) {
dest[len + i] = ' ';
}
dest[len + num_of_spaces] = '\0';
}
So, do you have any standard solution for me, so I don't reinvent the wheel?
I would do
add_spaces(char *dest, int num_of_spaces) {
int len = strlen(dest);
memset( dest+len, ' ', num_of_spaces );
dest[len + num_of_spaces] = '\0';
}
But as @self stated, a function that also gets the maximum size of dest (including the '\0'
in that example) is safer:
add_spaces(char *dest, int size, int num_of_spaces) {
int len = strlen(dest);
// for the check i still assume dest tto contain a valid '\0' terminated string, so len will be smaller than size
if( len + num_of_spaces >= size ) {
num_of_spaces = size - len - 1;
}
memset( dest+len, ' ', num_of_spaces );
dest[len + num_of_spaces] = '\0';
}