目录
前言
c++大大增加了对字符串的支持,除了使用c风格的字符串,还有内置的steing类。string类是c++里STL容器中的一个重要组成部分,在OJ中,和字符串有关的题目通常都以string类的形式出现。而且为了简单方便,在常规工作中都使用string类,很少有人使用c库中的字符串函数。那么接下来,我将带大家来了解一下string类的相关知识。
提示:以下是本篇文章正文内容,下面案例可供参考
一、标准库中的string类
1.string类对象的常见构造
string类有七个构造函数,下面我将挑几个常见的进行演示,如果有小伙伴想对其它进行详细了解,可以进入网址string::string - C++ Reference (cplusplus.com)。
代码如下:
int main()
{
string s1; //构造空的string类对象
cout << s1 << endl;
string s2("hello bit"); //用c字符串构造
cout << s2 << endl;
string s3(s2); //拷贝构造
cout << s3 << endl;
string s4 = "hello bit"; //这里发生运算符重载,相当于拷贝构造
cout << s4 << endl;
string s5(s4, 3, 4);//string (const string& str, size_t pos, size_t len);
cout << s5 << endl; // 从pos开始,后面的len个字符构造
const char* url = "http://www.cplusplus.com/reference/string/string/string/";
string s6(url, 4); //用字符串的前n个字符构造string类
cout << s6 << endl;
string s7(10, 'x'); //用10个x字符构造
cout << s7 << endl;
s7 = s2; //运算符重载
cout << s7 << endl;
return 0;
}
打印结果如下:
2、string类的遍历
2.1.下标+[]
int main()
{
string s2("hello bit");
for (size_t i = 0; i < s2.size(); ++i)
{
// s2.operator[](i)
s2[i] = 'x';
}
cout << endl;
for (size_t i = 0; i < s2.size(); ++i)
{
// s2.operator[](i)
cout << s2[i] << " ";
//cout << s2.at(i) << " ";
}
cout << endl;
}
size()功能:返回字符串有效字符长度。打印结果如下:
2.2迭代器遍历
我们在这里先简单展示迭代器的使用,在之后的文章中再详细介绍迭代器的原理。
// [begin(), end() ) end()返回的不是最后一个数据位置的迭代器,返回是最后一个位置下一个位置
// 也要注意的是,C++中凡是给迭代器一般都是给的[)左闭右开的区间
//