豆浆封口机厂:用C语言写一个函数,将两个字符串连接。

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/30 03:09:42
用C语言写一个函数,将两个字符串连接。

#include<stdio.h>
方法一:如mtcat所说,直接用strcat函数
方法二:编程实现strcat的功能
void main()
{ char s1[80],s2[80];
int i=0,j=0;
puts("input two strings:");
gets(s1);
gets(s2);
while(s1[i]!='\0') i++;
while((s1[i++]=s2[j++])!='\0');
printf("result:%s\n",s1);
}

1、实际上就是实现strcat这个字符串库函数,在vc自带的crt源码或者linux平台的glibc库中都有strcat的源码,自己可以查阅参考,看看库开发者是如何写代码的,对于学习C语言非常有用。
2、示例
#include <stdio.h>

char *strcat(char *str1, char *str2)
{
if((str1==NULL)||(str2==NULL)) throw "Invalide arguments!";
char *pt = str1;
while(*str1!='\0') str1++;
while(*str2!='\0') *str1++ = *str2++;
*str1 = '\0';
return pt;
}

int main()
{
char a[]= "markyuan";
char b[]= "yyyyy";
char *cat = strcat(a,b);
printf("%s\n",cat);
return 0;
}

char * string(char a[],char b[])
{
int c,d;
c=strlen(a); //计算字符串a的长度
d=strlen(b); //计算字符串b的长度
char p[c+d+1]; // 建立一个足够存放a和b的字符数组
strcpy(p,a); //将a拷进新建的数组中
strcat(p,b); //把b连接在字符串a的后面
return p;
}

void mystrcat(char *s1, char *s2)
{
while(*s1++);
s1--;
while(*s1++ = *s2++);
}

strcat(s1,s2);
合并字符串s1,s2,并将其结果保存在s1中.