C语言学习笔记之字符串拼接的2种方法——strcat、sprintf

本文为原创文章,转载请标明出处

1. 使用strcat进行字符串拼接

#include 
#include 
#include 

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 
#include 
#include 

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

你可能感兴趣的:(C语言学习笔记之字符串拼接的2种方法——strcat、sprintf)