C:如何将'x'空格附加/连接到字符串

Som*_*ing 12 c string spaces concatenation

我想在C中的字符串中添加一个可变数量的空格,并希望在我自己实现它之前知道是否有标准的方法.

到现在为止,我用了一些丑陋的方法来做到这一点:

  • 请假设在我调用以下任何函数之前,我注意为我想要连接的空间分配足够的内存

这是我使用的一种方式:

add_spaces(char *dest, int num_of_spaces) {
    int i;
    for (i = 0 ; i < num_of_spaces ; i++) {
        strcat(dest, " ");
    }
}
Run Code Online (Sandbox Code Playgroud)

这个性能更好,但看起来也不标准:

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

那么,你有什么标准的解决方案,所以我不重新发明轮子?

Ing*_*rdt 7

我会做

add_spaces(char *dest, int num_of_spaces) {
    int len = strlen(dest);
    memset( dest+len, ' ', num_of_spaces );   
    dest[len + num_of_spaces] = '\0';
}
Run Code Online (Sandbox Code Playgroud)

但正如@self所说,一个也获得dest最大大小的函数(包括该'\0'示例中的)更安全:

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

  • @self任何版本的`add_spaces()`只接受这两个参数取决于调用者检查适当的大小.我将添加一个也达到最大尺寸的解决方案. (2认同)