分析
strcat主要部分有两个:
1、找到字符串1的末尾。
2、将字符串2连接到1的末尾。
分别用循环完成以上两部。
注意:scanf(“%s”,str) 遇到空格便停止,因此用 %[^\n]%* c 同时吸收回车。
代码
#include <stdio.h>
#define LENGTH1 100
#define LENGTH2 100 //两个字符串的长度,2<=1
void strcat1(char *a, char *b)
{
while (*++a) //找到a[]的末尾
;
while (*a++ = *b++) //将b[]的内容放到a[]的末尾
;
*(a + 1) = '\0';
}
int main()
{
char str1[LENGTH1], str2[LENGTH2], c;
printf("Please enter string 1:\n");
scanf("%[^\n]%*c", str1); //“%[^\n]%*c”使字符串能够带空格
printf("Please enter string 2:\n");
scanf("%[^\n]", str2); //输入2
strcat1(str1, str2); //拼接1和2
printf("%s", str1);
return 0;
}
结果
strncat
把字符串2的前n个字符添加到字符串1的结尾处'。
#include <stdio.h>
#define LENGTH1 100
#define LENGTH2 100 //两个字符串的长度,2<=1
void strncat1(char *a, char *b, int n)
{
while (*++a) //找到a[]的末尾
;
for (size_t i = 0; i < n; i++)
*a++ = *b++;
*(a + 1) = '\0';
}
int main()
{
char str1[LENGTH1], str2[LENGTH2], c;
printf("Please enter string 1:\n");
scanf("%[^\n]%*c", str1);
printf("Please enter string 2:\n");
scanf("%[^\n]", str2);
strncat1(str1, str2,5); //拼接1和2(前n个字符)
printf("%s", str1);
return 0;
}