STL8-string容器
生活随笔
收集整理的這篇文章主要介紹了
STL8-string容器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- C 沒有 string 類,但提供了直接對字符數組、字符串操作的函數 -> 如 str_len()等等 -> 需要包含 “string.h”
?
#include<iostream> #include<string> using namespace std;//初始化 void test01() {string s1; //調用無參構造string s2(10, 'a');string s3("abcdefg");string s4(s3); //拷貝構造cout << s1 << endl;cout << s2 << endl;cout << s3 << endl;cout << s4 << endl; } /* 輸出為:aaaaaaaaaa abcdefg abcdefg *///賦值操作 void test02() {string s1;string s2("appp");s1 = "abcdefg";cout << s1 << endl;s1 = s2;cout << s1 << endl;s1 = 'a';cout << s1 << endl;s1.assign("jkl"); //成員方法cout << s1 << endl; } /* 輸出為: abcdefg appp a jkl *///取值操作 void test03() {string s1 = "abcdefg";//重載[]操作符for (int i = 0; i < s1.size(); i++){cout << s1[i] << " ";}cout << endl;//at成員函數for (int i = 0; i < s1.size(); i++){cout << s1.at(i) << " ";}cout << endl;//區別:[]訪問越界 直接掛了// at方式越界,拋異常 out_of_rangetry {cout << s1.at(100) << endl; //程序不會掛掉,因為at會拋異常//cout << s1[100] << endl; //程序掛掉,因為[]不會拋異常}catch (...) {cout << "越界!" << endl;} } /* 輸出為: a b c d e f g a b c d e f g 越界! *///拼接操作 void test04() {string s = "1234545";string s2 = "111";s += "abbbb";s += s2;cout << s << endl;string s3 = "3333";s2.append(s3); //將s3追加到s2的尾部cout << s2 << endl;string s4 = s2 + s3;cout << s4 << endl; } /* 輸出為: 1234545abbbb111 1113333 11133333333 *///查找操作 void test05() {string s = "abecasdgdgdg";//查找第一次出現的位置int pos=s.find("dg");cout << "pos:" << pos << endl;int rpos = s.rfind("dg");cout << "rpos:" << rpos << endl; } /* 輸出為: pos:6 rpos:10 *///替換操作 void test06() {string s = "abcdefg";//替換從pos開始n個字符為字符串str s.replace(pos,n,str)s.replace(0, 2, "111");cout << s << endl; } /* 輸出為: 111cdefg *///比較操作 void test07() {//比較區分大小寫,比較時參考字典順序,排越前越小string s1 = "abcd";string s2 = "abcde";if (s1.compare(s2) == 0)cout << "字符串相等!" << endl;elsecout << "不相等" << endl;} /* 輸出為: 不相等 *///子串操作 void test08() {string s1 = "abcd";//將位置1到位置3的字符串截取string s2=s1.substr(1, 3);cout << s1 << endl;cout << s2 << endl; } /* 輸出為: abcd bcd *///插入和刪除操作 void test09() {string s1 = "abcdefg";s1.insert(3, "1212");cout << s1 << endl;s1.erase(0, 2);cout << s1 << endl; } /* 輸出為: abc1212defg c1212defg */int main() {cout << "-------------test01----------" << endl;test01();cout << "-------------test02----------" << endl;test02();cout << "-------------test03----------" << endl;test03();cout << "-------------test04----------" << endl;test04();cout << "-------------test05----------" << endl;test05();cout << "-------------test06----------" << endl;test06();cout << "-------------test07----------" << endl;test07();cout << "-------------test08----------" << endl;test08();cout << "-------------test09----------" << endl;test09();return 0; }參考自https://blog.csdn.net/dark_cy/article/details/84791900
總結
以上是生活随笔為你收集整理的STL8-string容器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过conda安装imgaug
- 下一篇: 用SQL语句查看数据库数据量的大小