C++基礎-string型別-操作符
阿新 • • 發佈:2018-12-11
- 操作符
== // 關係操作符,從兩個字串的首字元根據字元的ASCII值開始比較
>
<
>=
<=
!=
+ //s1 + s2,把 s1 和 s2 連線成一個新字串, 返回新生成的字串
+= // s1 += s2, 把 s2追加到s1中
[] // str[n], 返回 str 中位置為 n 的字元,位置從 0 開始計數
- 舉例
#include <iostream> #include <string> using std::cout; using std::endl; using std::string; int main(void) { string str1("Hello, "); string str2 = "world!"; string str3 = str1 + str2; string str4("Hello, world!"); cout << "str1: " << str1 << endl; cout << "str5[1]: " << str5[1] << endl; if(str1 > str2) cout << "str2: " << str2 << endl; cout << "str3: " << str3 << endl; cout << "str4: " << str4 << endl; if(str3 == str4) { cout << "str3 == str4" << endl; } string str5(str1); str5 += str2; cout << "str5: " << str5 << endl; cout << "str5[1]: " << str5[1] << endl; if(str1 > str2) { cout << str1 << "大於" << str2 << endl; } else if(str1 == str2) { cout << str1 << "等於" << str2 << endl; } else { cout << str1 << "小於" << str2 << endl; } return 0; }
PC:~/WorkSpace/CPP/string/3.2.3$ ./str_operators.exe
str1: Hello,
str2: world!
str3: Hello, world!
str4: Hello, world!
str3 == str4
str5: Hello, world!
str5[1]: e
Hello, 小於world!