使用C语言实现字符串复制
一、概述
案例:使用C语言编写一个函数,来实现字符串的copy。
二、代码示例
#include <iostream>
using namespace std;
/**
* 使用数组 copy
* */
void mystrcopy(char *str1,char* str2){
int i =0;
while(str1[i]!='0'){
str2[i] = str1[i];
i++;
}
str2[i] = '\0';
}
/**
* 使用字符串copy
* */
void mystrcopy2(char *str1,char *str2){
while(*str1!='\0'){
*str2 = *str1;
str1++;
str2++;
}
*str2 = '\n';
}
int main(int argc, char const *argv[])
{
char *str1 = (char*)"my baby is luoluoyang";
cout << "str1:"<<str1<<endl;
char *str2;
// malloc(sizeof(str2))
mystrcopy2(str1,str2);
cout << "str2:"<<str2<<endl;
// free(str2);
return 0;
}
浙公网安备 33010602011771号