1 string 存取字符操作 2种方法
char& operator[](int n);//通过[]方式取字符
char& at(int n);//通过 at 方法获取字符
//[] 越界不会抛出异常 at方法 越界会抛出异常
string str1 = "hello";
char c = str1[1]; =>e
char ch = str1.at(1); =>e
2 抛出异常测试
[] 越界不会抛出异常,直接报错
void test() {
string str1 = "hello";//长度为5
try {
//长度为5,访问下标10,明显越界,
str1[10] = 'A'; //[] 越界不会抛出异常,直接报错
//str1.at(10) = 'A';//at方法 越界会抛出异常
}
catch (exception& e) {
cout << "捕获到异常" << e.what() << endl;
}
}
at方法 越界会抛出异常
void test() {
string str1 = "hello";//长度为5
try {
//长度为5,访问下标10,明显越界,
//str1[10] = 'A'; //[] 越界不会抛出异常,直接报错
str1.at(10) = 'A';//at方法 越界会抛出异常
}
catch (exception& e) {
cout << "捕获到异常" << e.what() << endl;
}
}
3 如果没有异常,会执行try里面的语句
try{
str1.at(1) = ‘A’;
}
A会替换str1中下标为1的字符
void test() {
string str1 = “hello”;//长度为5
cout << str1 << endl;
try {
str1.at(1) = 'A';//at方法 越界会抛出异常
}
catch (exception& e) {
cout << "捕获到异常" << e.what() << endl;
}
cout << str1 << endl;
}