简体   繁体   English

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

[英]C: How to append/concatenate 'x' spaces to a string

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

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: 但正如@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';
}
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. 所以在main假设你声明你的数组像char dest[100]然后用speces初始化你的字符串。

like 喜欢

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

So you not need even add_spaces(char *dest, int num_of_spaces) . 所以你甚至不需要add_spaces(char *dest, int num_of_spaces)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM