一、string类的字符操作
1、string定义:可变长的字符串
2、string字符串初始化,示例:
- string s = “hello world”;
- sting s1(“hello world2”);
- string *ps = new string(“hello world3”);
- string s4 = “”; //空字符串
3、string字符访问方式:使用[]或at函数
- cout << s1[3] << endl; //输出字符l
- cout << s1.at(4) << endl; //输出字符o
二者区别:越界情况[]不会报出异常,at函数会产生异常。
二、string类的特性(属性)
1、特性(*重点)
- int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素数) *
- int max_size()const; //返回string对象中可存放的最大字符串的长度 *
- int size()const; //返回当前字符串的大小 *
- int length()const; //返回当前字符串的长度
- bool empty()const; //当前字符串是否为空 *
- void resize(int len,char c); //把字符串当前大小置为len,并用字符c填充不足的部分
2、长度length、大小size(占有内存空间)此处相等,均不包含”\0”,常用size。
注:在C语言中strlen不包含”\0”而sizeof包含”\0”。
3、capacity规则:返回值总比它的size要大。
4、使用示例
- cout << s1.size() << endl; //前四种
- if(s4.empty() == true) {cout << “s4 is null\n”;} //第五种