赞
踩
方式一: 使用for循环
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- char* Mystrcpy(char *str1,char *str2){
- if(str1==NULL || str2==NULL){
- printf("str1是野指针或者str2是野指针");
- exit(-1);
- }
- char *demo=str1;
- for(int i=0;i<strlen(str2);i++){
- *(str1+i)=*(str2+i);
- }
- return demo;
- }
- int main(){
- char *str1;
- char *str2="happy";
- str1= (char*)malloc(sizeof(char)*10);
- Mystrcpy(str1,str2);
- printf("str1=%s \n",str1);
- return 0;
-
- }

方式二:使用while循环
- #include <stdio.h>
- #include <stdlib.h>
- char* Mystrcpy(char *str1,char *str2){
- if(str1==NULL || str2==NULL){
- printf("传递的数据中有野指针");
- exit(-1);
- }
- char *demo=str1;
- while(*str2!='\0'){
- *str1=*str2;
- str1++;
- str2++;
- }
- *str1='\0';
- return demo;
- }
- int main(){
- char *str1;
- char *str2="happy";
- str1 = (char*)malloc(sizeof(char)*10);
- Mystrcpy(str1,str2);
- printf("str1=%s\n",str1);
-
- return 0;
- }

方式三:在方式二上进行改进
- #include <stdio.h>
- #include <stdlib.h>
- char* Mystrcpy(char *str1,char *str2){
- if(str1==NULL || str2==NULL){
- printf("传递的数据中有野指针");
- exit(-1);
- }
- char *demo=str1;
- while(*str2!='\0'){
- *str1++=*str2++;
- }
- *str1='\0';
- return demo;
- }
- int main(){
- char *str1;
- char *str2="happy";
- str1 = (char*)malloc(sizeof(char)*10);
- Mystrcpy(str1,str2);
- printf("str1=%s\n",str1);
-
- return 0;
- }

方法四:在方法三的基础上再次该进
- #include <stdio.h>
- #include <stdlib.h>
- char* Mystrcpy(char *str1,char *str2){
- if(str1==NULL || str2==NULL){
- printf("传递的数据中有野指针");
- exit(-1);
- }
- char *demo=str1;
- while((*str1++=*str2++)!='\0');
- *str1='\0';
- return demo;
- }
- int main(){
- char *str1;
- char *str2="happy";
- str1 = (char*)malloc(sizeof(char)*10);
- Mystrcpy(str1,str2);
- printf("str1=%s\n",str1);
-
- return 0;
- }

这里顺带实现一下strncpy函数
- #include <stdio.h>
- #include <stdlib.h>
- char* Mystrncpy(char *str1,char *str2,int n){
- if(str1==NULL || str2==NULL){
- printf("传递的数据中有野指针");
- exit(-1);
- }
- if(n>sizeof(str2)){
- printf("你需要复制的字符串长度超出了被复制的字符串长度");
- exit(-1);
- }
- char *demo=str1;
- int i=0;
- while(i<n){
- *str1++=*str2++;
- i++;
- }
- *str1='\0';
- return demo;
- }
- int main(){
- char *str1;
- char *str2="happy";
- str1 = (char*)malloc(sizeof(char)*10);
- int n=3;
- Mystrncpy(str1,str2,n);
- printf("str1=%s\n",str1);
-
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。