C语言模拟实现strncpy、strcat
来源:互联网 发布:sql中values什么意思 编辑:程序博客网 时间:2024/05/16 14:49
模拟实现strncpy
先演示一下strncpy的效果:
代码如下:
#include <string.h>#include <stdio.h>void main(void){char string[100] = "Cats are nice usually";printf("Before: %s\n", string);strncpy(string, "Dogs", 4);strncpy(string + 9, "funn", 4);printf("After: %s\n", string);system("pause");}
运行结果:
通过以上演示可以看出,strncpy实现的是用一个固定的字符串去替换原字符串中的某段字符,可以设置一个循环,来实现字符的替换,如果它只有一个字符要替换,则循环执行一次,设置一个循环判断语句即可,循环次数等于要替换的字符数。
程序代码如下:
#include <Windows.h>#include <string.h>#include <stdio.h>#include <assert.h>char *mystrncpy(char *strDest, const char *strSource, size_t count){assert(strDest);assert(strSource);while (count--){*strDest++ = *strSource++;}return strDest;}void main(void){char string[100] = "Cats are nice usually";printf("Before: %s\n", string);mystrncpy(string, "Dogs", 4);mystrncpy(string + 9, "hola", 4);printf("After: %s\n", string);system("pause");return 0;}
模拟实现strcat,程序代码如下:
#include <Windows.h>#include <string.h>#include <stdio.h>#include <assert.h>char *mystrcat(char *strDest, const char *strSource){int len = strlen(strDest);assert(strDest);assert(strSource);char *ret = strDest;char *newstrDest = strDest + len; //新接的字符串开始位置while (*strSource){*newstrDest++ = *strSource++; //把要加的字符串一个一个copy过去}return ret;}int main(){char string[120];strcpy(string, "Hello world from ");strcat(string, "strcpy ");strcat(string, "and ");strcat(string, "strcat haha!");printf("String = %s\n", string);system("pause");return 0;}
运行结果如图:
实现程序功能方法有多种,不一定非得要死板的模仿哪一种方法,而是自己慢慢地去探索。
0 0
- C语言模拟实现strncpy、strcat
- C语言模拟实现strcpy、strncpy、strcmp、strcat、strstr
- [C语言]模拟实现strcpy/strncpy/strcat/strncat/strcmp/strncmp/strstr
- c语言模拟实现strcat
- C语言-模拟实现strcat
- strcpy/strncpy/strcat/strcmp/strlen函数的c语言实现
- 【C语言】模拟实现strcpy()、strncpy()函数
- 模拟实现strlen、strcpy、strncpy、strcat、strcmp
- C语言字符串相关库函数的实现strcpy、memcpy、strncpy、strcat、strncpy、memset、memcpy、strcpy
- 【C语言】模拟实现库函数strcat函数
- 【c语言】 模拟实现库函数strcat函数
- 【笔试题】C语言:模拟实现strcat
- C语言::模拟实现strcat函数
- 【c语言】模拟实现strcat()、strncat()函数
- 【c语言】模拟实现strcat函数
- 用c语言.模拟实现strcpy,strcat,strcat,memcpy,memmove
- C语言中strlen、strcpy、strncpy、strcat、strnact、strcmp、memcpy函数的实现
- C语言中strlen、strcpy、strncpy、strcat、strnact、strcmp、memcpy函数的实现
- 学生信息管理系统
- 常见的加密算法分类
- service
- 使用钩子函数获取全部的鼠标消息和键盘消息
- 背包问题
- C语言模拟实现strncpy、strcat
- 求和
- ViewPager 详解(一)---基本入门
- poj 1050 To The Max
- c#试题(一)
- UVA 12168 Cat vs. Dog(最大独立集)
- jsp到后台乱码问题的解决方案
- Netty 中文教程 (二) Hello World !详解
- torch7跑mnist例子出现No LuaRocks module found for weight-init问题