编写连接两个字符串函数strcat和字符串复制函数strcpy。

如题所述

第1个回答  推荐于2016-09-23
#include <stdio.h>
void strcpy(char *s1, char *s2)
{
if(s1==NULL || s2==NULL) return;
while(*s2 != '\0') *s1 ++ = *s2++;
*s1 = '\0';
}
void strcat(char *s1, char *s2)
{
if(s1==NULL || s2==NULL) return;
while(*s1 != '\0') s1 ++;
while(*s2 != '\0') *s1 ++ = *s2++;
*s1 = '\0';
}
int main(void)
{
char s1[100] = "abcd";
char s2[100] = "1234";
char s3[100] = "UVWXYZ";
strcat(s1, s2);
strcpy(s2, s3);
printf("%s\n", s1);
printf("%s\n", s2);
return 0;
}本回答被提问者采纳
第2个回答  2012-01-03
char *strcat(char *source,char *destin)
{
while(*source);
do{
*source++=*destin;
}while(*destin++);
}

char *strcpy(char *str1,char *str2)
{
char *p,*q;
if(str1==null and str2==null)return null;
p=str1;q=str2;
while(*p!='\0' &&*q!='\0'){*p++=*q++;}
return str1;
}
第3个回答  2012-01-03
百度百科中有追问

没 有 我还会问的吗?

追答

Strcat函数原型如下:
  char *strcat(char *strDest, const char *strSrc) //将源字符串加const,表明其为输入参数
  {
  char *address = strDest; //该语句若放在assert之后,编译出错
  assert((strDest != NULL) && (strSrc != NULL)); //对源地址和目的地址加非0断言
  while(*strDest) //是while(*strDest!=’\0’)的简化形式
  { //若使用while(*strDest++),则会出错,因为循环结束后strDest还会执行一次++,那么strDest
  strDest++; //将指向'\0'的下一个位置。/所以要在循环体内++;因为要是*strDest最后指
  } //向该字符串的结束标志’\0’。
  while(*strDest++ = *strSrc++)
  {
  NULL; //该循环条件内可以用++,
  } //此处可以加语句*strDest=’\0’;无必要
  return address; //为了实现链式操作,将目的地址返回
  }
* C语言标准库函数strcpy的一种典型的工业级的最简实现
  * 返回值:
  * 返回目标串的地址。
  * 对于出现异常的情况ANSI-C99标准并未定义,故由实现者决定返回值,通常为NULL。
  * 参数:
  * strDestination
  * 目标串
  * strSource
  * 源串
  ***********************/
  char *strcpy(char *strDestination, const char *strSource)
  {
  assert(strDestination && strSource);
  char *strD=strDestination;
  while ((*strDestination++=*strSource++)!='\0')
  NULL;
  return strD;
  }

相似回答