【C++】string (string类的常用接口 string类对象的容量操作 string类对象的访问及遍历操作 string类对象的修改操作)


string

string是一个专门管理字符数组的类。


标准库中的string类

在这里插入图片描述

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
  4. 不能操作多字节或者变长字符的序列。

在使用string类时,必须包含#include头文件以及using namespace std;


string类的常用接口

string() ----> 构造空的string类对象,即空字符串

string(const char* s) ----> 用C-string来构造string类对象

string(size_t n, char c) ---->string类对象中包含n个字符c

string(const string&s) ----> 拷贝构造函数

#include<iostream>
#include<string>
using namespace std;
void test_test1()
{
	string s1;
	string s2("西安市高陵区");
	string s3 = "西安市高陵区";
	string s4(10, '*');

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;

	string s5(s2);
	string s6 = s2;
	cout << s5 << s6 << endl;
}
int main()
{
	test_test1();
	return 0;
}

在这里插入图片描述

string的三种遍历方式:

迭代器 ---- 通用的访问方式
在这里插入图片描述
Iterators:行为上来说迭代器是一个像指针的东西。
begin:返回第一个位置的迭代器。
在这里插入图片描述

end:返回最后一个数据的下一个位置的迭代器。

void test_test2()
{
	string s1("1234");
	//1.
	for (size_t i = 0; i < s1.size(); ++i)
	{
		s1[i]++;
	}
	cout << s1 << endl;

	//2.
	for (auto& ch : s1)
	{
		ch--;
	}
	cout << s1 << endl;
	//反转一下
	size_t begin = 0, end = s1.size() - 1;
	while (begin < end)
	{
		swap(s1[begin++], s1[end--]);
	}
	cout << s1 << endl;
	//迭代器
	string::iterator it1 = s1.begin();
	while (it1 != s1.end())
	{
		*it1 += 1;
		++it1;
	}

	it1 = s1.begin();
	while (it1 != s1.end())
	{
		cout << *it1 << " ";
		++it1;
	}
	cout << endl;
}
int main()
{
	test_test2();
	return 0;
}
2345
1234
4321
5 4 3 2

在这里插入图片描述

反向迭代器:string::reverse_iterator

void test_string3()
{
	string s1("1234");
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}
int main()
{
	test_string3();
	return 0;
}
1 2 3 4
4 3 2 1

反向迭代器也可以认为是一个类似 指针,指针是倒着遍历的。


string类对象的容量操作

在这里插入图片描述

size; 返回字符串有效字符长度 。

length :返回字符串有效字符长度。

max_size():返回容量最大值

clear:清空有效字符。

void test_string4()
{
	string s("hello world");
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.max_size() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;
	s.clear();
	cout << s << endl;

	//空间不清
	cout << s << endl;
	cout << s.capacity() << endl;

}
11
11
2147483647
15
hello world


15

capacity: 返回空间总大小。

void TestPushBack()
{
	string s;
	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';

	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}

void test_string5()
{
	TestPushBack();
}

int main()
{
	test_string5();
	return 0;
}
capacity changed: 15
making s grow:
capacity changed: 31
capacity changed: 47
capacity changed: 70
capacity changed: 105

empty :检测字符串释放为空串,是返回true,否则返回false。

reserve:为字符串预留空间,提前开好空间,避免了扩容,提高效率

在这里插入图片描述
请求string的capacity去size改变,把capacity的容量改成n来适应插入n个数据。就是改变capacity。

void TestPushBack()
{
	string s;
	s.reserve(1000);
	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';

	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}

void test_string5()
{
	TestPushBack();
}

int main()
{
	test_string5();
	return 0;
}
capacity changed: 1007
making s grow:
capacity changed: 1510

resize :将有效字符的个数改成n个,多出的空间用字符c填充。

在这里插入图片描述
reserve影响的是capacity,只影响空间不会动数据,resize会改变string的长度,把string的长度改变到n,并且resize也会影响capacity。

void test_string6()
{
	string s1("hello world");
	s1.resize(5);
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	cout << s1 << endl << endl;

	string s2("hello world");
	s2.resize(15,'x');//在后面补齐
	cout << s2.size() << endl;
	cout << s2.capacity() << endl;
	cout << s2 << endl << endl;

	string s3("hello world");
	s3.resize(20,'x');
	cout << s3.size() << endl;
	cout << s3.capacity() << endl;
	cout << s3 << endl << endl;

}
int main()
{
	test_string6();
	return 0;
}
5
15
hello

15
15
hello worldxxxx

20
31
hello worldxxxxxxxxx

在这里插入图片描述

shrink_to_fit:缩减容量。
在这里插入图片描述

注意:

  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不会改变容量大小。

string类对象的访问及遍历操作

operator[] :返回pos位置的字符,const string类对象调用。

begin+ end: begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器。

rbegin + rend: begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器。

范围for :C++11支持更简洁的范围for的新遍历方式。

在这里插入图片描述

at和operator[]功能类似,获取第pos位置的字符,但是at的区别是,at发生越界后是抛异常。operator[]是断言报错。
bank和front是取第一个字符和最后一个字符。


string类对象的修改操作

在这里插入图片描述

push_back :尾插,在字符串后尾插字符c。

在这里插入图片描述

为了弥补push_back的缺陷,出现了append:

append :在字符串后追加一个字符串。

在这里插入图片描述

void test_string7()
{
	string s1("hello world");
	s1.push_back(' ');
	s1.push_back('!');
	s1.append("hello world");
	cout << s1 << endl;

	string s2("!!!!!!!");
	s1.append(s2);
	cout << s1 << endl;
}

int main()
{
	test_string7();
	return 0;
}
hello world !hello world
hello world !hello world!!!!!!!

但是这块最好用的还是operator+= :

operator+=: 在字符串后追加字符串str。

在这里插入图片描述

void test_string8()
{
	string s1("hello world");
	s1 += ' ';
	s1 += '!';
	s1 += "hello world";
	cout << s1 << endl;

	string s2("!!!!!!!");
	s1 += s2;
	cout << s1 << endl;
}

int main()
{
	test_string8();
	return 0;
}
hello world !hello world
hello world !hello world!!!!!!!

insert:插入数据

在这里插入图片描述

void test_string8()
{
	string s("hello world");
	s.insert(0, "bit");
	cout << s << endl;
	s.insert(9, "bit");
	cout << s << endl;
}

int main()
{
	test_string8();

	return 0;
}
bithello world
bithello bitworld

erase:删除字符

在这里插入图片描述

void test_string8()
{
	string s("hello world");
	s.insert(0, "bit");
	cout << s << endl;
	s.insert(9, "bit");
	cout << s << endl;

	s.erase(9, 3);
	cout << s << endl;

	s.erase(0, 3);
	cout << s << endl;
	
	s.erase(5, 30);
	cout << s << endl;

}

int main()
{
	test_string8();

	return 0;
}
bithello world
bithello bitworld
bithello world
hello world
hello

c_str: 返回C格式字符串。

find + npos:从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置。

rfind :从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置。

substr :在str中从pos位置开始,截取n个字符,然后将其返回。

注意:

  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不会改变容量大小。


想要了解更多关于string的知识请前往官方网站学习:https://legacy.cplusplus.com/

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
String对象数组是指一个数组的每个元素都是String型的对象。在编写代码时,可以使用以下方式声明和使用String对象数组: 1. 使用Array的构造函数声明并初始化String对象数组: ```java String[] arr = new String[]{"element1", "element2", "element3"}; ``` 这种方式使用Array的构造函数创建String对象数组,并通过花括号{}的元素赋值给数组的每个位置。 2. 使用数组的简化声明方式声明和初始化String对象数组: ```java String[] arr = {"element1", "element2", "element3"}; ``` 这种方式简化了数组的声明和初始化,直接在花括号{}列出元素即可。 3. 可以通过下标访问修改String对象数组的元素: ```java String element = arr = "newElement"; // 修改数组下标为1的元素 ``` 使用方括号[]和下标的方式可以访问修改数组的元素。需要注意的是,数组的下标从0开始,到数组长度-1为止。 总结:String对象数组是一个数组的每个元素都是String型的对象。可以使用Array的构造函数或简化声明方式来声明和初始化String对象数组,并通过下标来访问修改数组的元素。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [String对象和数组的异同](https://blog.csdn.net/m0_37058714/article/details/81165972)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Java入门篇(四)——数组](https://blog.csdn.net/weixin_42293337/article/details/94392864)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马尔科686

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值