c - C语言中如何连接两个字符串?

标签 c string

如何添加两个字符串?

我尝试了name = "derp"+ "herp";,但出现错误:

Expression must have integral or enum type

最佳答案

C 不支持其他一些语言所具有的字符串。 C 中的字符串只是一个指向以第一个空字符结尾的 char 数组的指针。 C 中没有字符串连接运算符。

使用strcat连接两个字符串。您可以使用以下函数来完成此操作:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

这不是最快的方法,但您现在不必担心。请注意,该函数将一 block 堆分配的内存返回给调用者,并传递该内存的所有权。当不再需要内存时,调用者有责任释放内存。

像这样调用函数:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

如果您确实对性能感到困扰,那么您会希望避免重复扫描输入缓冲区以查找空终止符。

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

如果您计划使用字符串进行大量工作,那么您最好使用对字符串具有一流支持的其他语言。

关于c - C语言中如何连接两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48459464/

相关文章:

c++ - 查找不重复的字符串排列

c++ - 我对 getline+strings 有什么不了解的地方?

java - 字符串实用程序拆分 - Linux

c - OpenCV视频采集和fps问题

c - 为什么 execvp() 使用 fork() 执行两次?

c - 虽然循环等待全局变量不触发

java - 根据 Java 中字符串的第 n 次出现拆分字符串

c++ - 如何将 .c 和 .h 文件存储在包含路径中,与当前项目的源代码分开

c - Switch 语句不执行案例 (c)

java - 为什么可能 arrayList 只显示一个字符串?