C++必修:STL用法之string

07-21 1028阅读

C++必修:STL用法之string

✨✨ 欢迎大家来到贝蒂大讲堂✨✨

🎈🎈养成好习惯,先赞后看哦~🎈🎈

所属专栏:C++学习

贝蒂的主页:Betty’s blog

1. C/C++中的字符串

1.1. C语言中的字符串

在 C 语言中,字符串是由字符组成的字符数组,以空字符 '\0' 作为结束标志。由于数组特点,字符串的大小在定义数组时就已经确定,无法更改。

	//数组大小为20
	char str[20] = "hello betty!\n";

当然我们可以通过动态内存分配来来解决这个问题,但无疑非常繁琐。

void Test1()
{
	char* str = NULL;
	int len = 0;
	// 初始分配一些内存
	str = (char*)malloc(10 * sizeof(char));
	if (str == NULL) {
		perror("malloc fail");
		return 1;
	}
	strcpy(str, "Hello");
	len = strlen(str);
	// 根据需要扩展字符串
	str = (char*)realloc(str, (len + 6) * sizeof(char));
	if (str == NULL) {
		perror("realloc fail");
		return 1;
	}
	strcat(str, " World");
	printf("%s\n", str);
	//最后释放内存
	free(str);
}

1.2. C++中的字符串

虽然C++兼容C语言,在C++中仍然可以使用C语言的字符串,但是C++自己实现了一个关于处理字符串的类–string,它提供了许多方便的操作和功能,使得字符串的处理更加安全和高效。下面是一个简单的string的使用:

void Test2()
{
	string str = "hello betty!";
	cout 
	string s1 = "hello betty!";
	//普通迭代器
	string::iterator it = s1.begin();//指向第一个位置
	while (it != s1.end())
	{
		cout 
		cout 
	string s1 = "hello betty!";
	//普通反向迭代器
	string::reverse_iterator rit = s1.rbegin();//指向最后一个字符位置
	while (rit != s1.rend())
	{
		cout 
		cout 
	//1. 使用我们的默认构造函数,不需要传参。
	string s1;
	s1 = "hello betty!";
	//2. 使用的是拷贝构造来初始化。
	string s2(s1);
	//3. 使用一个string的某段区间初始化,其中pos是字符串下标,npos是指无符号整数的最大值。
	string s3(s2, 1, 7);
	//4. 使用的是某个字符数组初始化。
	string s4("hello world!");
	//5. 使用的是某个字符数组前n个字符来初始化
	string s5("hello world!", 5);
	//6. 使用的是n个c字符初始化。
	string s6(7, 'a');
	//7. 使用的是某段迭代器区间初始化。
	string s7(s1.begin(), s1.end());
	//赋值运算符重载初始化
	string s8 = "hello betty!";
	cout 
	string s("hello betty!");
	cout 
	string s;
	size_t sz = s.capacity();
	cout 
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout 
	string s1("");//空串
	string s2("hello ");
	if (s1.empty())
	{
		cout 
		cout 
		cout 
		cout 
	string s1("hello world!");
	cout 
		cout 
	string s1("hello world!");
	cout 
	string s1("hello world!");
	cout 
	string s1("hello betty!");
	for (int i = 0; i 
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]