linux下C编程(二)之 strcpy strncpy
2015-10-17 22:14
609 查看
简单实现
char *my_strcpy(char *dest_str,char *sour_str);
#include <stdio.h> //函数的声明 char *my_strcpy(char *dest_str,char *sour_str); //函数的具体实现 char *my_strcpy(char *dest_str,char *sour_str) { //一般不建议对传入的指针参数直接进行使用 char *pstr1 = dest_str; char *pstr2 = sour_str; //判断是否满足条件 (防御式编程) if(dest_str == NULL || sour_str == NULL || dest_str == sour_str) return dest_str; //执行 while(*pstr2){ *pstr1++ = *pstr2++; } *pstr1 = '\0'; //打印 printf("%s",dest_str); return dest_str; } int main(int argc,char *argv[]) { char *str1 = "hello.world\n"; char str2[100]={0}; my_strcpy(str2,str1); re
简单的实现
char *my_strncpy(char *dest_str, char *sour_str ,int n);
#include <stdio.h> //函数声明 char *my_strncpy(char *dest_str, char *sour_str ,int n); //函数具体实现按 char *my_strncpy(char *dest_str, char *sour_str ,int n) { char *pstr1 = dest_str; char *pstr2 = sour_str; int size = sizeof(sour_str); int i ; //是否满足条件 if(dest_str == NULL || sour_str == NULL || size < n) return NULL; // 执行 for(i = 0 ;i < n ;++i) { *pstr1++ = pstr2[i]; } *pstr1 = '\0'; //输出 printf("%s\n",dest_str); return dest_str; } int main(int argc,char *argv[]) { int n; char *str1 = "hello,world!"; char str2[100] = {0}; char *str; printf("please input values n: "); scanf("%d",&n); str = my_strncpy(str2,str1,n); if(str == NULL) printf("your input error\n"); return 0; }
相关文章推荐
- Linux命令格式及帮助命令详解
- [Linux 小技巧] Ubuntu 14.04 下编译、安装、配置最新开发版 GoldenDict
- Linux用户用户管理和组管理命令使用方法
- linux----man
- linux下C编程(一)之 hello world
- Linux中 ibus输入法中 全拼和双拼的问题
- Install KVM (QEMU) on CentOS 7 / RHEL 7
- Linux 2.6内核中新的锁机制--RCU
- Centos6.5 下编译64位 Hadoop 2.2.0
- 如何参与linux内核开发
- Linux下vim使用
- Linux下 SVN使用
- Linux常见命令
- linux读书笔记4
- linux下libphenom的测试代码
- 对centos6下时间同步(ntp)操作的讨论
- linux 读书笔记2
- centos7通过firewalld更改sshd端口
- linux读书笔记1
- 利用Linux系统函数实现线程池(C++)