Chinaunix首页 | 论坛 | 博客
  • 博客访问: 55468
  • 博文数量: 51
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 410
  • 用 户 组: 普通用户
  • 注册时间: 2018-08-26 01:30
文章分类

全部博文(51)

文章存档

2020年(2)

2018年(49)

我的朋友

分类: C/C++

2018-08-29 19:49:32

 03. 编程实现strcpy


    我们知道strcpy是字符串复制函数。

    定义于:

点击(此处)折叠或打开

  1. string.h

声明:

点击(此处)折叠或打开

  1. char *strcpy(char *dest, const char *src)
原型:

点击(此处)折叠或打开

  1. #ifdef _NC_RESTRICT
  2. char *strcpy(char *restrict dest, const char *restrict src)
  3. #else
  4. char *strcpy(char *dest, const char* src)
  5. #endif
  6. {
  7.     char *ret = dest;
  8.     while (*dest++ = *src++)
  9.         ;
  10.     return ret;
  11. }

1. 使用strlen实现

点击(此处)折叠或打开

  1. /*
  2.  * exercise01.c
  3.  *
  4.  * Created on: 2012-11-5
  5.  * Author: xiaobin
  6.  *
  7.  * Huawei face questions
  8.  */

  9. #include <stdio.h>
  10. #include <string.h>

  11. char *strcpy1(char *dest, const char *src)
  12. {

  13.     char *ret = dest;
  14.     int len = strlen(src);

  15.     int i = 0;
  16.     while (len-- != 0) {
  17.      ret[i] = src[i];
  18.      i++;
  19.     }

  20.     return ret;
  21. }


  22. int main(int argc, char* argv[])
  23. {
  24.     char *s = "hello,world";
  25.     char *d;
  26.     strcpy1(d, s);
  27.     printf("%s\n", d);
  28.     return 0;
  29. }
 计算源串的长度,然后循环赋值。

2. 无strlen实现

点击(此处)折叠或打开

  1. /*
  2.  * exercise01.c
  3.  *
  4.  * Created on: 2012-11-5
  5.  * Author: xiaobin
  6.  *
  7.  * Huawei face questions
  8.  */

  9. #include <stdio.h>
  10. #include <string.h>

  11. char *strcpy1(char *dest, const char *src)
  12. {

  13.     char *ret = dest;

  14.     int i = 0;
  15.     while (*src != 0) {
  16.      ret[i] = *src;
  17.      i++;
  18.      *src++;
  19.     }

  20.     return ret;
  21. }


  22. int main(int argc, char* argv[])
  23. {
  24.     char *s = "hello,world";
  25.     char *d;
  26.     strcpy1(d, s);
  27.     printf("%s\n", d);
  28.     return 0;
  29. }

参考文章:

阅读(359) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~