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;
}

  

posted @ 2021-02-27 16:42  liweikuan  阅读(1148)  评论(0编辑  收藏  举报