目录
1.operator+ 组合字符串
string (1) | string operator+ (const string& lhs, const string& rhs); |
---|---|
c-string (2) | string operator+ (const string& lhs, const char* rhs); string operator+ (const char* lhs, const string& rhs); |
character (3) | string operator+ (const string& lhs, char rhs); string operator+ (char lhs, const string& rhs); |
1.string operator+ (const string& lhs, const string& rhs) 组合对象lhs和rhs
2.string operator+ (const string& lhs, const char* rhs) 组合对象lhs和字符串rhs
string operator+ (const char* lhs, const string& rhs) 组合字符串lhs和对象rhs
3.string operator+ (const string& lhs, char rhs) 组合对象lhs和字符rhs
string operator+ (char lhs, const string& rhs) 组合字符lhs和对象rhs
string str1("hello ");
string str2("bit ");
char s[] = "world ";
char c = '!';
string ret1, ret2, ret3, ret4, ret5, ret6;
ret1 = str1 + str2;//hello bit
ret2 = str2 + str1;//bit hello
ret3 = str1 + s;//hello world
ret4 = s + str1;//world hello
ret5 = str1 + c;//hello !
ret6 = c + str1;//!hello
2.relational operators 关系运算判断
(1) | bool operator== (const string& lhs, const string& rhs); bool operator== (const char* lhs, const string& rhs); bool operator== (const string& lhs, const char* rhs); |
---|---|
(2) | bool operator!= (const string& lhs, const string& rhs); bool operator!= (const char* lhs, const string& rhs); bool operator!= (const string& lhs, const char* rhs); |
(3) | bool operator< (const string& lhs, const string& rhs); bool operator< (const char* lhs, const string& rhs); bool operator< (const string& lhs, const char* rhs); |
(4) | bool operator<= (const string& lhs, const string& rhs); bool operator<= (const char* lhs, const string& rhs); bool operator<= (const string& lhs, const char* rhs); |
(5) | bool operator> (const string& lhs, const string& rhs); bool operator> (const char* lhs, const string& rhs); bool operator> (const string& lhs, const char* rhs); |
(6) | bool operator>= (const string& lhs, const string& rhs); bool operator>= (const char* lhs, const string& rhs); bool operator>= (const string& lhs, const char* rhs); |
3.swap 交换字符串
void swap (string& x, string& y) 交换对象x和对象y
string str1("hello");
string str2("bit");
cout << "begin: str1: " << str1 << " str2: " << str2 << endl;
swap(str1, str2);
cout << "last: str1: " << str1 << " str2: " << str2 << endl;
//begin: str1: hello str2 : bit
//last : str1: bit str2 : hello
4.operator>> 输入
istream& operator>> (istream& is, string& str)
cin输入以空字符结尾,作为一次输入
5.operator<< 输出
ostream& operator<< (ostream& os, const string& str)
6.getline 输入
(1) | istream& getline (istream& is, string& str, char delim); |
---|---|
(2) | istream& getline (istream& is, string& str); |
1.istream& getline (istream& is, string str, char delim) 向对象str中输入内容,delim为手动设置的结束标志
2.istream& getline (istream& is, string str) 向对象str中输入内容,默认结束标志为换行符(回车)
getline可以解决cin不能读取空格字符的缺陷
string str;
getline(cin, str);//输入123 456
cout << str << endl;//输出123 456
getline(cin, str2, '#');//输入123#456
cout << str2 << endl;//输出123