将字符串str1复制为字符串str2的三种解决方法

xiaoxiao2021-02-27  340

http://www.jb51.net/article/42165.htm 1.自己编写函数,将两个字符串进行复制

#include<iostream> using namespace std; int main(){ char str1[]="I love China!",str2[20]; void Strcpy(char *p1,char *p2); Strcpy(str2,str1); cout<<"str1: "<<str1<<endl; cout<<"str2: "<<str2<<endl; return 0; } void Strcpy(char *p2,char *p1){ int i=0; for(;*p1!='\0';p1++,p2++){ *p2=*p1; } *p2='\0'; }

2.使用函数库重的strcpy函数

#include<iostream> #include<string.h> using namespace std; int main() { char str1[]="I love China!",str2[20]; strcpy(str2,str1); cout<<"str1: "<<str1<<endl; cout<<"str2: "<<str2<<endl; return 0; }

3.定义两个字符串变量,然后直接进行赋值

#include<iostream> #include<string> using namespace std; int main(){ string str1="I love China!",str2; str2=str1; cout<<"str1: "<<str1<<endl; cout<<"str2: "<<str2<<endl; return 0; }
转载请注明原文地址: https://www.6miu.com/read-3873.html

最新回复(0)