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

标签 c string concatenation spaces

我想在 C 中的字符串中添加可变数量的空格,想知道是否有标准的方法来实现,然后再自己实现。

到目前为止,我使用了一些丑陋的方法来做到这一点:

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

这是我使用的一种方式:

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

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

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

那么,你们有没有适合我的标准解决方案,这样我就不会重新发明轮子了?

最佳答案

我愿意

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

但正如@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';
}

关于C:如何将 'x' 空格附加/连接到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855807/

相关文章:

c++ - 连接 boost::array 和 std::string

group-by - DB2 独特 + xmlagg 查询

c - 将字符串文字放在变量之前

c - 使用 Code::Blocks 调试 C

javascript - 查找字符串中有错误的单词

c - 如何通过终端将段落读取为 C 中的单个字符串?

c - 赋值从指针生成整数,无需强制转换 c[a0][4] ="YES";我不明白出了什么问题 int 整数 t 已经声明了

python - 通过索引的二维数组更改二维数组

php - 在网页中编译 C 程序时出错

c - 主函数内的 sizeof(Array_Name) VS 用户定义函数内的 sizeof(Array_Name)