系统函数strcat的功能是把两个字符串连接成一个字符串

系统函数strcat的功能是把两个字符串连接成一个字符串,使用这一函数时要求头文件包含:#include <string.h>。函数调用形式是strcat(字符串1,字符串2),函数执行后把字符串2的内容连接到字符串1的后面。问题中可以先计算字符串1的长度,从字符串1的长度+1位置(也就是字符串1结束符的位置)开始,利用循环依次将字符串2的所有字符拷贝到字符串1。遍历字符串元素时,可以利用字符串结束符结束循环。
注意:拷贝过程结束后,要确保连接后的字符串有字符串结束符,否则会产生错误。
数据要求
问题中的常量:#define MAXNUM 200 /*定义数组的最大长度*/
问题的输入:char str1 /*字符串1,初始的字符串*/;char str2 /*字符串2*,要连接的字符串/
问题的输出:char str1 /*字符串1,最终输出的字符串*/
初始算法
1.初始化字符串1和字符串2;
2.调用函数mystrcat把字符串2连接到字符串1的后面;
3.输出字符串1;
4.结束。
算法细化
步骤2的细化
    2.1 定义变量i,j
    2.2 利用循环i找出字符串str1的长度
         2.2.1 不是结束标志,i++
         2.2.2 是结束标志,退出循环
    2.3 利用循环j把字符串str2的内容接到str1的后面
2.3.1不是结束标志,j++
         2.3.2是结束标志,退出循环
    2.4 给str1后面赋值'\0'
    2.5 函数结束
程序代码如下:
#include “stdio.h”
#define MAXNUM 200
void mystrcat(char str1[],char str2[])
{
int i,j;
/*计算str1的长度,循环结束后i的值等于str1的长度加1*/
for(i=0; str1 [i]!='\0';i++);
/*在str1后添加str2的每个字符*/
for(j=0; str2 [j]!='\0';j++)
  str1 [i+j]= str2 [j];
/*最后一定要加上字符串结束符*/
str1 [i+j]='\0';
}
main()
{
/*定义两个字符数组str1和str2,注意str1要能容纳连接后的字符串*/
char str1[MAXNUM],str2[MAXNUM];
/*输入str1和str2*/
printf("\nPlease input str1:\n");
gets(str1);
jdfkdkf.wallinside.com;
kdjkdf.wallinside.com;
dkd.wallinside.com;
tinyurl.com/p7o77lf;
tinyurl.com/oqlqd2q;
tinyurl.com/qhpt8kd;
tinyurl.com/puk336j;
tinyurl.com/q3xn2tn;
tinyurl.com/oo7b6yy;
about.me/haodwoe;
about.me/kd_dfe;
about.me/fdkem;
about.me/dkert;
about.me/heiche5785;
about.me/gianne3039;
about.me/gatica4110;
about.me/ommen98970;
about.me/rexfor8060;
about.me/hertle1899;
about.me/halas60883;
about.me/bixel48543;
about.me/kieger4295;
about.me/ringla8107;
about.me/mackni5533;
about.me/gaible5322;
about.me/galleg7138;
about.me/course3512;
about.me/splitt4062;
about.me/hackl57465;
about.me/schouw8474;
about.me/labarb2965;
about.me/donath4838;
about.me/waggen3465;
about.me/mccaw13558;
about.me/waldor3732;
about.me/volker7054;
about.me/davi30933;
about.me/toye51419;
about.me/loeza64996;
about.me/lobing6035;
about.me/amaya60220;
about.me/loawar1298;
about.me/mcginn6340;
about.me/francy6714;
about.me/eyerma3419;
about.me/gouldm8648;
about.me/goens64400;
about.me/warrel3380;
about.me/stanko1046;
printf("Please input str2:\n");
gets(str2);
/*调用函数进行处理*/
mystrcat(str1,str2);
/*打印输出结果*/
printf("Catenated str1=%s",str1);
}
分析
结果为:
Please input str1:
hello!
Please input str2:
kitty
Catenated str1=hello!kitty
函数mystrcat也可以使用指针方式实现,main函数不用改动,代码如下:
void mystrcat(char *pstr1,char *pstr2)
{
/*将指针pstr1拨到字符串末尾*/
while(*pstr1) pstr1++;
/*在pstr2后添加pstr2的每个字符,注意循环最后一次拷贝了'\0'*/
while(*pstr1++=* pstr2++);
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值