如何在C中连接两个字符串?

Lev*_*i H 126 c string

如何添加两个字符串?

我试过了name = "derp" + "herp";,但是我收到了一个错误:

表达式必须具有整数或枚举类型

Dav*_*nan 159

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;
}
Run Code Online (Sandbox Code Playgroud)

这不是最快的方法,但你现在不应该担心.请注意,该函数将一堆堆分配的内存返回给调用者,并传递该内存的所有权.free当不再需要时,调用者有责任记忆.

像这样调用函数:

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

如果您确实碰巧遇到性能问题,那么您可能希望避免重复扫描输入缓冲区以查找空终止符.

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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • concat()可以用asprintf()代替,即asprintf(&res,"%s%s",str1,str2),其中res是未初始化的char*; (10认同)
  • 使用“stpcpy”的第一个版本的性能略有提高,它返回指向第一个字符串末尾的指针:“strcpy(stpcpy(result, s1), s2);” (4认同)

BLU*_*IXY 16

#include <stdio.h>

int main(){
    char name[] =  "derp" "herp";
    printf("\"%s\"\n", name);//"derpherp"
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


mmd*_*bas 15

David Heffernan 在他的回答中解释了这个问题,并编写了改进的代码.见下文.

通用功能

我们可以编写一个有用的可变参数函数来连接任意数量的字符串:

#include <stdlib.h>       // calloc
#include <stdarg.h>       // va_*
#include <string.h>       // strlen, strcpy

char* concat(int count, ...)
{
    va_list ap;
    int i;

    // Find required length to store merged string
    int len = 1; // room for NULL
    va_start(ap, count);
    for(i=0 ; i<count ; i++)
        len += strlen(va_arg(ap, char*));
    va_end(ap);

    // Allocate memory to concat strings
    char *merged = calloc(sizeof(char),len);
    int null_pos = 0;

    // Actually concatenate strings
    va_start(ap, count);
    for(i=0 ; i<count ; i++)
    {
        char *s = va_arg(ap, char*);
        strcpy(merged+null_pos, s);
        null_pos += strlen(s);
    }
    va_end(ap);

    return merged;
}
Run Code Online (Sandbox Code Playgroud)

用法

#include <stdio.h>        // printf

void println(char *line)
{
    printf("%s\n", line);
}

int main(int argc, char* argv[])
{
    char *str;

    str = concat(0);             println(str); free(str);
    str = concat(1,"a");         println(str); free(str);
    str = concat(2,"a","b");     println(str); free(str);
    str = concat(3,"a","b","c"); println(str); free(str);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

  // Empty line
a
ab
abc
Run Code Online (Sandbox Code Playgroud)

清理

请注意,在不需要时,应释放已分配的内存以避免内存泄漏:

char *str = concat(2,"a","b");
println(str);
free(str);
Run Code Online (Sandbox Code Playgroud)

  • calloc的参数是向后的.他们应该算大小.由于sizeof(char)被定义为1,因此你可以在这里得到它的乘法身份. (3认同)

orl*_*rlp 8

你应该使用strcat,或者更好strncat.Google it(关键字是"连接").

  • 注意:`strncat()`是一个非常难以正常使用的函数.很快,不看手册,你指定`strncat()`的长度是多少?如果你说"缓冲区的长度",你只是很好地证明了我的观点.它有一个反直觉的界面,当你有足够的数据安全使用它时,你不需要首先使用该功能 - 还有其他,更快,更有效的替代品(如`strcpy()`或`memmove()`)可以用来代替.几乎无论"我应该使用什么"这个问题,`strncat()`都不是答案. (8认同)

小智 7

我假设你需要一次性的东西.我假设你是一名PC开发人员.

使用Stack,Luke.到处使用它.永远不要使用malloc/free进行小额分配.

#include <string.h>
#include <stdio.h>

#define STR_SIZE 10000

int main()
{
  char s1[] = "oppa";
  char s2[] = "gangnam";
  char s3[] = "style";

  {
    char result[STR_SIZE] = {0};
    snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
    printf("%s\n", result);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果每个字符串10 KB是不够的,那么在大小上添加零并且不要打扰, - 无论如何,它们将在范围的末尾释放它们的堆栈内存.


Mah*_*esh 5

你不能在C中添加像这样的字符串文字.你必须创建一个大小为字符串文字的缓冲区1 +字符串文字2 +一个字节用于空终止字符并将相应的文字复制到该缓冲区并确保它是空终止的.或者你可以使用库函数strcat.