c - 如何在 C 中将 char 连接到 char*?

标签 c char concatenation prepend

如何将 char c 添加到 char* myChar 之前? c 的值为 "A"myChar 的值为 "LL"。如何将 c 添加到 myChar 以生成 "ALL"

最佳答案

这应该有效:

#include <string.h>    
char * prepend(const char * str, char c)
{
    char * new_string = malloc(strlen(str)+2);  // add 2 to make room for the character we will prepend and the null termination character at the end
    if (new_string) {
        new_string[0] = c;
        strcpy(new_string + 1, str);
    }
    return new_string;
}

请记住在使用完后 free() 生成的新字符串,否则会发生内存泄漏。

此外,如果您要对同一个字符串执行数百或数千次此操作,那么还有其他方法可以更有效地执行此操作。

关于c - 如何在 C 中将 char 连接到 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8569452/

相关文章:

c - 循环中的execl和wget命令

java - Java 中无法将 int 转换为 string

c - 为什么函数 `memchr()` 使用 `int` 作为 `char` 类型的参数?

javascript - Gulp 处理文件名

python - 多尺度 CNN - Keras 实现

c# - FileSystemWatcher 无法访问文件,因为它正被另一个进程使用

c - 如何读取逗号分隔字符串中的名称和整数值?

c - 变量点等于数组中的元素

C 字符串删除 - 此代码如何工作?

C 指针问题连接字符串