在C语言中,连接两个字符串可以使用strcat()
函数或者手动实现。
strcat()
函数:strcat()
函数用于连接两个字符串,将第二个字符串追加到第一个字符串的末尾。
#include <stdio.h> #include <string.h> int main() { char str1[100] = "Hello"; char str2[50] = " World"; strcat(str1, str2); printf("连接后的字符串:%s\n", str1); return 0; }
输出结果为:
连接后的字符串:Hello World
手动实现字符串连接可以使用循环将第二个字符串的每个字符逐个复制到第一个字符串的末尾,并在末尾添加结束符\0
。
#include <stdio.h> int main() { char str1[100] = "Hello"; char str2[50] = " World"; int i, j; i = 0; while (str1[i] != '\0') { i++; } j = 0; while (str2[j] != '\0') { str1[i] = str2[j]; i++; j++; } str1[i] = '\0'; printf("连接后的字符串:%s\n", str1); return 0; }
输出结果同样为:
连接后的字符串:Hello World