C语言中的字符串函数有如下这些

  • 获取字符串长度

    • strlen
  • 长度不受限制的字符串函数
    • strcpy
    • strcat
    • strcmp
  • 长度受限制的字符串函数
    • strncpy
    • strncat
    • strncmp
  • 字符串查找
    • strstr
    • strtok
  • 错误信息报告
    • strerror

接下来看看如何实现它们

长度不受限制的字符串函数

strcpy

我们看看文档是怎样说的,如下

strcpy文档

char * strcpy ( char * destination, const char * source );

Copy string

字符串拷贝(字符串复制)

Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

复制由字符指针source指向的C字符串到另一个字符数组中,该字符数组字符指针destination指向

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

为避免溢出,由destination指向的字符数组的大小需要足够长,足够包含住源字符串(包含'\0')

综上,可以知道

  1. 会将源字符串中的 '\0' 拷贝到目标空间,源字符串必须以 '\0' 结束。
  2. 目标空间必须足够大,以确保能存放源字符串。

怎么实现拷贝?

int main()
{
char arr1[] = "abcdefghi";
char arr2[] = "bit";
// 把arr2的内容拷贝到arr1中
//strcpy(arr1, arr2);
// 怎么拷贝? my_strcpy(arr1, arr2);
printf("%s\n", arr1);
return 0;
}

实现

断言指针不为空是个好习惯~

//char* my_strcpy(char* dest, char* src)
// src加上const,为什么?因为我们只需要拷贝,不需要改动源字符串,防止发生修改,所以加上const修饰
char* my_strcpy(char* dest, const char* src)
{
assert(dest != NULL);
assert(src != NULL); while (*src != '\0')
{
*dest = *src;
dest++;
src++;
}
*dest = *src; // '\0'
// 返回目的空间的起始地址
return dest;
}

源字符串拷贝到目的空间,寻找'\0',不是'\0'的就执行*dest = *src,把源字符赋值给目的空间,然后两个指针都往后偏移,也就是都进行++,当*src为'\0'时,说明源字符串已经到结尾了,就退出这个循环,直接将'\0'赋值给*dest,最后返回dest

可以进行优化,如下

char* my_strcpy(char* dest, const char* src)
{
assert(dest != NULL);
assert(src != NULL);
// 优化
while (*src != '\0')
{
*dest++ = *src++;
}
*dest = *src; // '\0'
// 返回目的空间的起始地址
return dest;
}

当然还可以继续优化,变得更加简洁,直接将*dest++ = *src++作为判断条件,同时还会执行操作,如下

char* my_strcpy(char* dest, const char* src)
{
assert(dest != NULL);
assert(src != NULL);
// 优化
// 拷贝src指向的字符串到dest指向的空间,包含'\0'
char* rest = dest;
while (*dest++ = *src++)
{
;
}
// 返回目的空间的起始地址
return rest;
}

最新文章

  1. NSNotification --关于通知
  2. mysql中的 IN和FIND_IN_SET的查询问题
  3. iphone document 图片存储和读取
  4. linux杂记(三)linux指令介绍
  5. WPF: 本地化(Localization) 实现
  6. 为什么要学习Java EE
  7. [PGM] Bayes Network and Conditional Independence
  8. jq实现上传头像并实时预览功能
  9. 2018-01-08 学习随笔 SpirngBoot整合Mybatis进行主从数据库的动态切换,以及一些数据库层面和分布式事物的解决方案
  10. eslint 代码缩进 报错及解决
  11. 微服务(Microservices)和服务网格(Service Mesh)架构概念整理
  12. maven生命周期和插件详解
  13. React native采坑路 Running 1 of 1 custom shell scripts
  14. Java Base64编码
  15. myeclipse安装maven
  16. Linux删除多余内核
  17. wp 去除google字体加载
  18. jQuery 四舍五入
  19. ubuntu(14.04) 安装ssh,并使用root用户登录
  20. 9.SQL存储过程实例详解

热门文章

  1. luogu4464:莫比乌斯反演,积性函数和伯努利数
  2. idea加载maven项目遇见的坑---2
  3. 为什么ConcurrentHashMap,HashTable不支持key,value为null?
  4. frame 和 iframe
  5. SpringCloud之服务降级
  6. 分布式流转开发常见报错FAQ
  7. 使用docker-compose配置mysql数据库并且初始化用户
  8. nacos服务注册之服务器端Raft
  9. 更新啦!第 59 期《HelloGitHub》开源月刊
  10. MySQL提权 通过UDF