一、string是什么?
string类是专门的字符串操作的一个类,非常的强大。
二、string与char* 的区别:
char* 呢就是指向字符数组地址的指针,然后我们提供了一个string.h,包括很多字符串操作函数,strlen、strcat、strcpy、strcmp等。string则是一个类,将以上内容封装起来,使得字符串更加灵活,方式更多,管理更合理;string这个类,我们使用的时候不用考虑内存的分配与释放,不用担心越界崩溃。
三、string类的使用:
(1)构造函数
#include<iostream> #include<string> using namespace std; int main() { string str;//无参的构造函数 //empty()为判空函数,若为空输出1,不空输出0 cout << str << " " << endl;//输出为空 cout << str.empty() <<endl;//输出为1 string str1(5,'a');//将5个字符'a'赋值给str1 cout << str1 << " " << endl;//输出为aaaaa cout << str1.empty() <<endl;//输出0 string str2("abcdefg");//字符串初始化 cout << str2 << endl;//输出abcdefg string str3("abcdefg",3);//字符串初始化并规定只输出前三个 cout << str3 << endl;//输出abc string str4("abcdefg",2,4);//从下标为2的字符开始输出4个字符 cout << str4 << endl;//cdef string str5(str1);//拷贝构造,将str1的内容赋值给str5 cout<< str5<< endl;//输出aaaaa return 0; }
(2)属性
2.1 capacity()
//vc6.0的编译环境 void StrPro() { string str; cout << str.capacity() << endl;//0 string str1("asdfadag"); cout << str1.capacity() << endl;//31 string str2(30,'a'); cout << str2.capacity() << endl;//31 string str3(32,'a'); cout << str3.capacity() << endl;//63 string str4(64,'a'); cout << str4.capacity() << endl;//95 }
特别注意:
(1)如果在vc6.0的编译环境里,字符串为空时,它的容量为0;当字符串的长度在1~31时,它的容量为31,;当长度在32~63时,它的容量为63... ...
我们可以发现一个规律:字符串的长度如果为空,容量为0;当字符串的长度在1~31,则容量大小为31个,以后每次超过原来容量的大小,就在原来的基础上增加32个(即31+n*32个容量)
(2)如果在vs2005的编译环境里,我们可以发现这样一个规律:当字符串的长度在0~31,容量大小为15个,以后每次超过原来容量大小,就在原来的基础上增加16个(即15+n*16个容量)
2.2 reserve() 修改字符串容量的大小,只能变大不能变小
//vc6.0的编译环境 void StrPro() { string str1("a"); cout << str1.capacity() << endl;//31 str1.reserve(32);//将容量变大 cout << str1.capacity() << endl;//63 str.reserve(1);//将容量变小,但容量并没有变小 cout << str1.capacity() << endl;//63 }
2.3 length() 字符串的长度
zise() 字符串的个数
void StrPro() { string str1("ascde"); cout << str1.length() << endl;//5 cout << str1.size() << endl;//5 }
2.4 size() 重新设置字符个输,容量的变化和我们上面的讲的一样
//vc6.0的编译环境 void StrPro() { string str2("abcdefg"); cout << str2.capacity() << endl;//31 str2.resize(30); cout << str2 << endl;//abc cout << str2.capacity() << endl;//31 str2.resize(32); cout << str2.capacity() << endl;//63 }
(3)用下标访问字符的两种方式
void fun() { string str2("abcdefg"); cout << str2[2] << endl;// c cout << str2.at(3) << endl;// d }
修改容量的大小,只能变大不能变小