利用C语言,编写一个程序,将两个字符串连接起来,不要用strcat或strncat函数。
/*
编写一个程序,将两个字符串连接起来,不要用strcat或strncat函数。
*/
#include <stdio.h>
int main()
{
char a[100] = "sreere", b[5] = "1234";
int i = 0;
while (a[i] != '\0')
i++;
int j = 0;
while (b[j] != '\0')
j++;
int k = 0;
char c[i + j + 1]; // 重新定义一个数组,放两个连接起来的字符串,避免两个那两个字符串过大,而破溃
for (; k < i; k++)
{
c[k] = a[k];
}
for (k = 0; k < j; k++)
{
c[i + 1 + k] = c[i + k]; // 注意 数组是从 0 开始的,
c[i + k] = b[k];
}
printf("将 %s 接到 %s 后面,得到的结果是 %s\n", b, a, c);
}
运行结果:
将 1234 接到 sreere 后面,得到的结果是 sreere1234