|
C 语言拼接字符串
一、使用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); // 把firstName复制到name中
- strcat(name, lastName); // 把lastName追加到name中
- printf("%s\n", name);
- return 0;
- }
复制代码 二、 使用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));
- // 发送格式化输出到name指定的字符串
- sprintf(name, "%s%s", firstName, lastName);
- printf("%s\n", name);
- return 0;
- }
复制代码
|
|