在使用C的char*字符串时,我们常常会纠结以下的一些问题:
- 分配的char*数组空间是否足够
- 如何获取char*字符串的长度
- 如何拼接两个char*字符串
可以说,string的出现,大家再也不用烦恼上面的一些问题了,string是一个类,里面封装了很多常用的操作函数以及成员变量,基本上可以满足我们绝大部分的字符串操作的需要。但是在使用string的过程中,还是有一些点需要注意的。
1、string的substr函数
string的substr函数的原型如下:
basic_string substr(
size_type _Off = 0,
size_type _Count = npos
) const;
其第一个参数表示在string的指向的字符串的偏移量;第二个参数表示从这个偏移位置开始要截取的字符串长度。若substr()函数的_Off参数超过string的size时,程序就会抛出异常。
string a = "1";
string b = a.substr(3, 1); //crash
异常的内容如下:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Aborted
2、string的erase函数
下面是string的erase函数的其中一个原型:
basic_string& erase(
size_type _Pos = 0,
size_type _Count = npos
);
其第一个参数表示需要删除字符串的起始偏移量;第二个参数表示要删除的字符串长度。若erase()函数的_Pos参数超过basic_string的size,程序就会抛出异常。
string sVal = "abc";
sVal.erase(4, 10); //crash
异常的内容如下:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::erase
Aborted
对于string的两个成员函数substr和erase,函数内部并不会对传入的第一个参数,即substr函数的_Off和erase函数的_Pos进行参数合法性检验,当这两个函数的第一个参数的值大于string字符串的长度时程序就会抛出异常了。
3、string的构造函数
下面是string的其中一个构造函数:
string (const char* s);
参数s表示一个C字符串。当传入的C字符串为NULL的时候,就会抛出异常。
char *p = NULL;
string str(p);
异常的内容如下:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct NULL not valid
Aborted
如果传入的C字符串是空的话,就直接抛出异常,估计是担心用户后续会对这个空串进行操作。