青衣 发表于 2021-7-30 21:16:47

C语言字符串拼接

1、使用strcat进行字符串拼接#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *firstName = "Theo";
    char *lastName = "Tsao";
    char *name = (char *) malloc(strlen(firstName) + strlen(lastName));
    strcpy(name, firstName);
    strcat(name, lastName);
    printf("%s\n", name);
    return 0;
}
2、使用sprintf进行字符串拼接#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *firstName = "Theo";
    char *lastName = "Tsao";
    char *name = (char *) malloc(strlen(firstName) + strlen(lastName));
    sprintf(name, "%s%s", firstName, lastName);
    printf("%s\n", name);
    return 0;
}



文档来源:51CTO技术博客https://blog.51cto.com/u_15318120/3236804
页: [1]
查看完整版本: C语言字符串拼接