Three solutions for copying a string str1 into a string str2

  • 2020-04-02 01:57:34
  • OfStack

1. Write your own function to copy the two strings

#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. Use library heavy strcpy functions

#include<iostream>
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. Define two string variables and assign them directly

#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;
}

Related articles: