1. 为什么学习string类?
1.1 C语言中的字符串
C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
2. 标准库中的string类
2.1 string类(了解)
1. 字符串是表示字符序列的类
2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信息,请参阅basic_string)。
4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
总结:
1. string是表示字符串的字符串类
2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;
4. 不能操作多字节或者变长字符的序列。
在使用string类时,必须包含#include头文件以及using namespace std;
2.2 string类的常用接口说明
1. string类对象的常见构造
(constructor)函数名称 | 功能说明 |
string() (重点) | 构造空的string类对象,即空字符串 |
string(const char* s) (重点) | 用C-string来构造string类对象 |
string(size_t n, char c) | string类对象中包含n个字符c |
string(const string&s) (重点) | 拷贝构造函数 |
int main()
{
string s1;
string s2("hello world");
string s3 = s1;//构造函数初始化
string s4(s2);
//以下几个不是特别重要,只需要有印象即可
string s5(s2, 1, 6);//从s2的下标为1的开始到下标为6的初始化到s5;
cout << s5 << endl;
string s6(s2, 1, 100);
cout << s6 << endl;//从s2的下标为1的开始到100的初始化到s7(如果字符串提前结束,那就到结束的地方为止);
string s7(s2, 1);
cout << s7 << endl;//从s2的下标为1的开始到结束的初始化到s6;
string s9(10, 'x');//将s9初始化为10个'x'的支付串
cout << s9 << endl;
string s10 = s2;//赋值运算符重载
cout << s10 << endl;
s1 = "world";//赋值运算符重载
cout << s1 << endl;
s1 = 'x';//赋值运算符重载
cout << s1 << endl;
return 0;
}
2. string类对象的容量操作
函数名称 | 功能说明 |
size(重点) | 返回字符串有效字符长度 |
length | 返回字符串有效字符长度 |
capacity | 返回空间总大小 |
empty (重点) | 检测字符串释放为空串,是返回true,否则返回false |
clear (重点) | 清空有效字符 |
reserve (重点) | 为字符串预留空间** |
resize (重点) | 将有效字符的个数该成n个,多出的空间用字符c填充 |
注意:
1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
2. clear()只是将string中有效字符清空,不改变底层空间大小。
3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。
int main()
{
string s1;
string s2("hello wrold");
//max_size()表示这个字符串最大能开多大的空间,
//但是很多时候,这个大小基本上是虚构的,字符串根本开不了这么多,所以这个成员函数基本没有意义
//cout << s1.max_size() << endl;
//s1.reserve(s1.max_size());
//size()返回的是字符串中有效字符的个数
//capacity()返回的是这个字符串开辟了多少个支付的空间
/*cout << s1.size() << endl;
cout << s1.capacity() << endl;//这里出来的是15,其实上是16,给了一块空间给标识空间'\0';
cout << s2.size() << endl;
cout << s2.capacity() << endl;*/
//提前开辟好字符串所需要的空间
//reserver会为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。
//还有就是reserver并不会将string的空间变小(vs环境下),(g++环境下会改变string的空间大小)
/*s1.reserve(100);
cout << s1.capacity() << endl;*/
/*s2.reserve(10);
cout << s2 << endl;
cout << s2.capacity() << endl;
s2.reserve(100);
cout << s2 << endl;
cout << s2.capacity() << endl;
s2.reserve(10);
cout << s2 << endl;
cout << s2.capacity() << endl;*/
//这里我们来看一下vs的扩容机制,将代码放在这里下面会贴出,vs和g++下的两种不同情况
/*size_t old = s1.capacity();
cout << old << endl;
for (size_t i = 0; i < 500; i++)
{
s1.push_back('x');
if (old != s1.capacity())
{
cout << s1.capacity() << endl;
old = s1.capacity();
}
}
*/
}
int main()
{
string s1("hello world");
cout << s1.size() << endl;
cout << s1.capacity() << endl;
cout << s1 << endl;
// 当输入resize的 n> capacity 时-> 扩容+尾插
//s1.resize(100);
s1.resize(100, 'x');
cout << s1.size() << endl;
cout << s1.capacity() << endl;
cout << s1 << endl;
// size < n < capacity -> 尾插
string s2("hello world");
cout << s2.size() << endl;
cout << s2.capacity() << endl;
cout << s2 << endl;
s2.resize(12);
cout << s2.size() << endl;
cout << s2.capacity() << endl;
cout << endl;
// n < size -> 删除数据,保留前n个,但是不会改变这个字符串开辟的空间
string s3("hello world");
cout << s3.size() << endl;
cout << s3.capacity() << endl;
cout << s3 << endl;
s3.resize(5);
cout << s3.size() << endl;
cout << s3.capacity() << endl;
string s5;
s5.resize(100, '#');
cout << s5 << endl;
return 0;
}
3. string类对象的访问及遍历操作
函数名称 | 功能说明 |
operator[] (重点) | 返回pos位置的字符,const string类对象调用 |
begin+ end | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
rbegin + rend | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
范围for | C++11支持更简洁的范围for的新遍历方式 |
int main()
{
string s1("hello world");
cout<<s1.size()<<endl;
cout << s1.length() << endl;
for (int i = 0; i < s1.size(); i++)
{
s1[i];
cout << s1[i];
cout << s1.operator[](i) << " ";//这两种方法都是等价的,同样这种方式也能达到修改的目的
s1[i] = 'x';
}
cout << endl;
//这里还有一种方法是用迭代器,可以将这种方法视为一种指针的方法
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it;
++it;//同样这个也能达到修改的目的
}
cout << endl;
for (auto e : s1)
{
cout << e << " ";
}
cout << endl;
//下面采用rbegin的方法可以使迭代器从后面开始遍历
string::reverse_iterator it1 = s1.rbegin();
while (it1 != s1.rend())
{
//*it1 = 'x';
cout << *it1 << " ";
++it1;
}
cout << endl;
return 0;
}
4. string类对象的修改操作
函数名称 | 功能说明 |
push_back | 在字符串后尾插字符c |
append | 在字符串后追加一个字符串 |
operator+= (重点) | 在字符串后追加字符串str |
c_str(重点) | 返回C格式字符串 |
find + npos(重点) | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 |
rfind | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 |
substr | 在str中从pos位置开始,截取n个字符,然后将其返回 |
//不太重要
//insert 和 erase 是 string中的插入和删除
int main()
{
string s1("hello world");
s1.insert(5, "xxxx");//从在下标为5的位置插入字符串
cout << s1 << endl;
s1.insert(0, 1, 'x'); //insert在头插的时候有点不一样,得前面或者下面迭代器的
方法才能达到头插
s1.insert(s1.begin(), 'y');
cout << s1 << endl;
s1.erase(5, 4);//在下标为5的位置向后删除四个字符
cout << s1 << endl;
s1.erase(5);//下标为五之后的全部删除(缺省参数)
cout << s1 << endl;
return 0;
}
replace和find
int main()
{
string s1("hello world hello xuzhiyuan");
cout << s1 << endl;
// 所有的空格替换为20%
size_t pos = s1.find(' ', 0);//从下标0开始找' '返回' '的下标
while (pos != string::npos)
{
s1.replace(pos, 1, "20%");
// 效率很低,能不用就不要用了
pos = s1.find(' ', pos + 3);
}
cout << s1 << endl;
string s2("hello world hello bit");//以空间换时间的新的替换模式
cout << s2 << endl;
string s3;
for (auto ch : s2)
{
if (ch == ' ')
{
s3 += "20%";
}
else
{
s3 += ch;
}
}
cout << s3 << endl;
s2.swap(s3);//这个是string内部自己重载的swap,于std中的swap不一样
cout << s2 << endl;
return 0;
}
c_str
int main()
{
string filename("Test.cpp");
FILE* fout = fopen(filename.c_str(), "r");//C++兼容C语言,但是在字符串的表示形式上还是有不一样,所以设计了c_str
char ch = fgetc(fout);
while (ch != EOF)
{
cout << ch;
ch = fgetc(fout);
}
return 0;
}
rfind 和 find
int main()
{
string s1("Test.cpp");
string s2("Test.tar.zip");
size_t pos1 = s1.rfind('.');//从字符串尾部开始查找
if (pos1 != string::npos)
{
//string suff = s1.substr(pos1, s1.size() - pos1);//从下标为posl的位置向后找s1.size() - pos1个全部赋值给suff
string suff = s1.substr(pos1);
cout << suff << endl;
}
size_t pos2 = s2.rfind('.');
if (pos2 != string::npos)//用于判断是否找到
{
string suff = s2.substr(pos2);
cout << suff << endl;
}
string str("https://legacy.cplusplus.com/reference/string/string/substr/");
string sub1, sub2, sub3;
pos1 = str.find(':');
sub1 = str.substr(0, pos1 - 0);
cout << sub1 << endl;
pos2 = str.find('/', pos1+3);//从posl后开始找'/'
sub2 = str.substr(pos1 + 3, pos2 - (pos1 + 3));
cout << sub2 << endl;
sub3 = str.substr(pos2 + 1);//从下标pos2+1开始全部赋值给sub3
cout << sub3 << endl;
return 0;
}
find_first_not_of
int main()
{
std::string str("Please, replace the vowels in this sentence by asterisks.");
std::size_t found = str.find_first_not_of("abc");//从str中找"abc"中包含的字符,不包含在"abc"内的str字符,全部被改写为'*'
while (found != std::string::npos)
{
str[found] = '*';
found = str.find_first_not_of("abc", found + 1);
}
std::cout << str << '\n';
string s1("xxxx");
string s2 = "xxxx";
return 0;
}
find_last_of
void SplitFilename(const std::string& str)
{
std::cout << "Splitting: " << str << '\n';
std::size_t found = str.find_last_of("/\\");//从str末尾开始找,str中找这个字符串"/\\"中包含的字符,返回下标
std::cout << " path: " << str.substr(0, found) << '\n';
std::cout << " file: " << str.substr(found + 1) << '\n';
}
int main()
{
std::string str1("/usr/bin/man");
std::string str2("c:\\windows\\winhelp.exe");
SplitFilename(str1);
SplitFilename(str2);
return 0;
}