string容器----賦值操作
阿新 • • 發佈:2021-01-26
技術標籤:C++string賦值操作
1.string中的賦值操作大致有以下幾種型別:
- string &operator=(const char *s); //char*型別的字串 賦值給當前的字串
- string &operator=(const string &s); //把字串s賦值給當前的字串
- string &operator=(char c); //字元賦值給當前的字串
- string &assign(const char *s); //把字串s賦值給當前的字串
- string &assign(const char *s,int n); //把字元中的前n個字元賦值給當前的字串
- string &assign(const string &s); //把字串s賦值給當前字串
- 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; }