string类

string类文档
与其他的标准库类型一样,想要使用string类型,必须包含相关的头文件。且string类是位于std命名空间中的。但在实际的项目中,最好避免在头文件中使用using namespace std;,因为这样会引入整个std命名空间,可能会导致命名冲突。

#include<string>
using namespace std;

常用构造函数

函数名 功能
string() 创建一个空字符串
string(const char* s) 使用c风格字符串初始化字符串
string(const string& str) 拷贝构造函数
void test() {
	string s1; //创建一个空字符串
	string s2(&quot;hello world&quot;); //使用 hello world 初始化字符串 s2
	string s3(s2); //拷贝构造 s3

}##

string类对象的修改

函数名 功能
operator+= 将一个字符串连接到另一个字符串的末尾
c_str 返回c格式字符串
find 从pos位置往后找字符c,返回该字符在字符串中的位置
substr 在str中从pos位置开始,截取n个字符,并将其返回
rfind 从pos位置往前找字符c,返回该字符在字符串中的位置
//operator+=
int main() {
	string s1("hello ");
	string s2("world");
	s1 += s2;
	cout << s1 << endl;
}
//c_str
int main() {
	string str("hello world");

	cout << str << endl;
	cout << str.c_str() << endl;

	str += '\0';
	str += "world";

	cout << str << endl; // 一直输出到末尾
	cout << str.c_str() << endl; //遇到 \0 就结束
}
int main() {
	//将网址分割
	string url("https://cplusplus.com/reference/string/string/find/");

	size_t i = url.find(':');
	cout << url.substr(0, i) << endl;

	size_t j = url.find('/', i + 3);
	cout << url.substr(i + 3, j - (i + 3)) << endl;

	cout << url.substr(j + 1) << endl;
}

string类对象的访问及遍历

函数名 功能
operator[] 通过下标访问单个字符
迭代器
范围for
int main() {
	string s1("hello world");

	//1.operator[]
	cout << s1[2] << endl;

	//2.迭代器
		//将 s1 字符的AscII码减一
	string s3(s1);
	string::iterator it = s3.begin();
	while (it != s3.end()) {
		*it -= 1;
		++it;
	}
	cout << s3 << endl;
		//反向迭代器
	string s4(s1);
	string::reverse_iterator rit = s4.rbegin();
	while (rit != s4.rend()) {
		cout << *rit << endl;
		++rit;
	}

	//3.范围 for()
	for (auto s5 : s1) {
		cout << s5 << endl;
	}
}

string类对象的容量

函数名 功能
size 返回字符串有效字符长度
capacity 返回字符串容量
empty 检查字符串是否为空,是返回true,否返回false
clear 清空字符串
reserve 为字符串预留空间
resize 将有效字符的个数改成n个,多出的空间用字符c填充
void test() {
	string str("hello world");
	cout << str.size() << endl;
	cout << str.capacity() << endl;
	cout << str.empty() << endl;

	string str2(str);
	str2.clear();//只将 size 清零,不改变 capacity 的大小

	string str3(str);
	str3.reserve(10);//当设置的空间小于所需要的空间时,会自动增容
	//cout << str3.capacity() << endl;
	//cout << str3 << endl;

	//str3.resize(50);// resize(n);当字符数大于n时,只显示n个字符;当字符数小于n时,会以 \0 进行填充
	str3.resize(50, 'k');//使用指定字符 'k' 进行填充
	cout << str3 << endl;
}
posted @   羡鱼OvO  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示