目录
🌞专栏导读
🌛为什么学习string类?
⭐C语言中的字符串
🌛标准库中的string类
⭐基本使用string
//使用string类前需要包含头文件< string >;
#include<string>
//创建一个string类对象;
string str;
//创建并初始化对象;
string s1("hello world");
string s2 = "hellow world";\
//使用[]或at()函数来访问字符串中的单个字符。但是at()函数会进行边界检查,避免越界访问;
string str = "hello world";
cout << str[0] << endl;
cout << str.at(1) << endl;
//可以使用加号运算符+将两个字符串拼接起来,也可以使用append()函数将一个字符串添加到另一个字符串的末尾;
string str1 = "hello";
string str2 = "world";
string str3 = str1 + str2; // 将str1和str2拼接起来
string str4 = str1.append(str2); // 将str2添加到str1的末尾
str+='a'; // 向str末尾添加一个字符'a'
//使用cin向string类对象中输入数据(遇到空格读取结束);
string str;
cin >> str;
//使用getline函数向string类对象中输入数据(遇到换行符读取结束);
string str;
str.getline(); //或者可以这样写___getline(cin,str);
//使用cout输出string类对象的内容;
string str;
cout << str << endl;
⭐string类的常用接口
operator[]
:返回当前字符串中指定位置的字符;at(size_t pos)
:返回当前字符串中指定位置的字符,并进行边界检查;front()
:返回当前字符串中的第一个字符。;back()
:返回当前字符串中的最后一个字符;c_str()
:c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同。这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
string str = "hello world";
cout << str[0] << endl;
cout << str.at(1) << endl;
string str = "hello world";
cout << str.front() << endl;
cout << str.back() << endl;
string str = "hello world";
cout << str.c_str() << endl;
empty()
:判断当前字符串是否为空;size()
:返回当前字符串的字符数,不包含'\0'
;length()
:返回当前字符串的字符数,不包含'\0'
;capacity()
:返回当前字符串容量,即可以存储的字符数;reserve()
:为当前字符串分配指定的容量,即扩容;resize()
:扩容并初始化;operator+
:将两个字符串拼接起来;append()
:将一个字符串添加到另一个字符串的末尾;
string str1 = "hello";
string str2 = "world";
string str3 = str1 + str2; // 将str1和str2拼接起来
string str4 = str1.append(str2); // 将str2添加到str1的末尾
insert()
:在指定位置插入一个字符串;
string str = "hello world";
cout << str.insert(0, "aaaa") << endl; //在位置0处插入字符串
cout << str.insert(0, 5, 'a') << endl; //在位置0处插入5个字符'a'
erase()
:删除指定位置的一个字符或一段字符;
string str = "hello world";
cout << str.erase(0,5) << endl; //删除从位置0开始的5个字符
cout << str.erase() << endl; //清空字符串
substr()
:返回一个子串,包含从指定位置开始的指定数量的字符;
string str = "hello world";
//返回字符串中从位置0处开始的长度为3的字串
string substr = str.substr(0, 3);
find()
:在当前字符串中查找指定子串的位置;rfind()
:在当前字符串中从后往前
查找指定子串的位置;compare()
:将当前字符串与另一个字符串进行比较;
⭐总结:
🌛范围for的使用
范围for循环
是C++11
新增的一种语法结构,用于遍历容器类中的元素。它可以遍历数组、容器类等可迭代的对象,使得程序员可以更加简洁地遍历容器中的元素,而不必关心迭代器的细节。
string str = "hello world";
for (auto ch : str)
{
cout << ch << ' ';
}
cout << endl;
可以发现,它比我们之前所用的for循环更加方便。