C++ STL 容器 string
阿新 • • 發佈:2020-12-25
1 string
string內部含有一個char*字串
2 string構造方式
- 無參構造
string str;
- 字串構造
string str("abcd");
- 拷貝構造
- n個相同字元
string str(10, 'k'); //初始化為10個k
3 string賦值操作
可以有以下操作:
void string_test() { string str1; str1 = "str1"; cout << "str1 = " << str1 << endl; string str2 = str1; cout << "str2 = " << str2 << endl; string str3 = "a"; cout << "str3 = " << str3 << endl; string str4; str4.assign("str4"); cout << "str4 = " << str4 << endl; string str5; str5.assign("123456789", 5); cout << "str5 = " << str5 << endl; string str6; str6.assign(str5); cout << "str6 = " << str6 << endl; string str7; str7.assign(10, 'k'); cout << "str7 = " << str7 << endl; }
結果為:
4 string拼接
可以使用的是 += 以及append, 例子如下:
void string_test1() { string str1 = "str1"; str1 += "str"; cout << "str1 = " << str1 << endl; str1 = "str1"; str1 += 's'; cout << "str1 = " << str1 << endl; str1 = "str1"; string str2 = "str2"; str1 += str2; cout << "str1 = " << str1 << endl; str1 = "str1"; str1.append("str"); cout << "str1 = " << str1 << endl; str1 = "str1"; str1.append(str2); cout << "str1 = " << str1 << endl; str1 = "str1"; str1.append("abcdefg", 4); //拼前四個字元 cout << "str1 = " << str1 << endl; str1 = "str1"; str1.append("0123456789", 2, 3); //從第二(從0開始數)個字元開始拼三個字元 cout << "str1 = " << str1 << endl; str1 = "str1"; }
5 查詢和替換
find測試:
void string_find_test() { string str1 = "abcdefg"; int position = str1.find("de", 2); //find有兩個引數, 第一個是要查詢的字元 cout << "position: " << position << endl; //或者子串, 第二個引數是開始查詢的位置, position = str1.find("df", 2); //第二個引數的預設值為0,返回值是找到的 cout << "position: " << position << endl; //起始位置的下標,如果未找到就返回-1 position = str1.rfind("de", 2); //rfind跟find的區別是:rfind是從右向左 cout << "position: " << position << endl; //查詢. }