string容器----赋值操作

1.string中的赋值操作大致有以下几种类型:

  1. string &operator=(const char *s);  //char*类型的字符串 赋值给当前的字符串
  2. string &operator=(const string &s);  //把字符串s赋值给当前的字符串
  3. string &operator=(char c);  //字符赋值给当前的字符串
  4. string &assign(const char *s);  //把字符串s赋值给当前的字符串
  5. string &assign(const char *s,int n);  //把字符中的前n个字符赋值给当前的字符串
  6. string &assign(const string &s);  //把字符串s赋值给当前字符串
  7. string &assign(int n, char c);  //用n个字符赋值给当前字符串
    #include<iostream>
    #include<string>
    using namespace std;
    
    void test1()
    {
    	string s1;  //char*类型的字符串 赋值给当前的字符串
    	s1="hello world"; 
    	cout<<"s1 = "<<s1<<endl;
    	
    	string s2; //把字符串s赋值给当前的字符串
    	s2=s1; 
    	cout<<"s2 = "<<s2<<endl;
    	
    	string s3;  //字符赋值给当前的字符串
    	s3='a';
    	cout<<"s3 = "<<s3<<endl; 
    	
    	string s4;  //把字符串s赋值给当前的字符串
    	s4.assign("hello world");
    	cout<<"s4 = "<<s4<<endl;
    	
    	string s5;  //把字符中的前n个字符赋值给当前的字
    	s5.assign("hello world",5); 
    	cout<<"s5 = "<<s5<<endl;
    	
    	string s6;//把字符串s赋值给当前字符串
    	s6.assign(s5);
    	cout<<"s6 = "<<s6<<endl;
    	
    	string s7;  //用n个字符赋值给当前字符串
    	s7.assign(3,'a');
    	cout<<"s7 = "<<s7<<endl;
    }
    int main()
    {
    	test1();
    	return 0;
     } 

猜你喜欢

转载自blog.csdn.net/sang_12345/article/details/113105777
今日推荐