1. 程式人生 > 其它 >string容器----賦值操作

string容器----賦值操作

技術標籤:C++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,s5_1;  //把字元中的前n個字元賦值給當前的字
    	s5.assign("hello world",5); 
    //	s5_1.assign(s1,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;
     }