gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:36:29 25 4
gpt4 key购买 nike

如何添加两个字符串?

我尝试了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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com