STL 小白学习(2) string

时间:2023-03-09 13:28:24
STL 小白学习(2) string
 #include <iostream>
using namespace std;
#include <string> //初始化操作
void test01() {
//初始化操作
string s1;
string s2(, 'a');
string s3("abc");
string s4(s3); cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl; }
//赋值操作
void test02() {
//赋值操作
string s1;
string s2("appasd");
s1 = "";
cout << s1 << endl;
s1 = s2;
cout << s1 << endl;
s1 = 'a';
cout << s1 << endl; //成员方法 assign
s1.assign("jsk");
cout << s1 << endl; } //取值操作
void test03() {
//取值操作
string s1 = "abashjdsa"; //重载[]操作符
for (int i = ; i < s1.size(); i++) {
cout << s1[i] << " ";
}
cout << endl; //也提供了成员方法
for (int i = ; i < s1.size(); i++) {
cout << s1.at(i) << " ";
}
cout << endl; //区别
//[] 访问越界直接挂
//at(i) 抛出异常
try {
cout << s1.at()<<endl;
}
catch (...) {
cout << "越界 Error...!" << endl;
} }
//拼接操作
void test04() {
//+= 重载
string s = "";
cout << s << endl;
s += "";
cout << s << endl;
string s2 = "abc";
s += s2;
cout << s << endl;
//append 成员函数重载
string s3 = "";
s.append(s3);
cout << s << endl;
//等号重载
string s4 = s + s3;
cout << s4 << endl; } //string 查找与替换
void test05() {
string s = "fgabcdefg";
//s.find 查找第一次出现的位置
int pos = s.find("z");
cout << "pos: " << pos << endl;//没有 return -1
//s.rfind 查找最后一次出现的位置
pos = s.rfind('g');
cout << "pos: " << pos << endl; }
//替换
void test06() {
//替换
string s = "abcdefg";
s.replace(, , ""); //将0位置开始的2个 ab替换成1111
cout << s << endl;
}
//比较
void test07() {
//比较 相等返回0
string s1 = "abcd";
string s2 = "abc4"; if (s1.compare(s2) == ) {
cout << "相等" << endl;
}
else {
cout << "不相等!" << endl;
} }
//字串操作
void test08() {
string s = "abcsdsfsadas";
string substring = s.substr(, );//取s的从1位置开始的3个字符的字串
cout << substring << endl; }
//插入 删除
void test09() {
string s = "asfasddfsa";
s.insert(, "");//在s[1]位置前插入123
cout << s << endl;
s = "";
s.erase(, );//删除 s[0]开始的4个字符
cout << s << endl;
}
int main() {
test09();
}