質問

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:

  • Please assume that before I called any of the below functions, I took care to have enough memory allocated for the spaces I want to concatenate

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';
}

他のヒント

void add_spaces(char *dest, int num_of_spaces) {
    sprintf(dest, "%s%*s", dest, num_of_spaces, "");
}

Please assume that before I called any of the below functions, I took care to have enough memory allocated for the spaces I want to concatenate

So in main suppose you declared your array like char dest[100] then initialize your string with speces.

like

char dest[100];
memset( dest,' ',sizeof(dest)); 

So you not need even add_spaces(char *dest, int num_of_spaces).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top