【C++】string类常用接口

一、string类

STL的六大组件:STL的六大组件

  1. 字符串是表示字符序列的类
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型)。
  4. string类是basic_string模版类的一个实例,它使用char来实例化basic_string模版类,并用char_traits和allocator作为basic_string的默认参数。
  5. 注意,这个类独立于所以使用的编码来处理字节:如果用来处理多字节或变长字节(如UTF-8)的序列,这个类的所以成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模版类的别名,typedef basic_string<char, char_traits, allocator> string;
  4. 不能操作多字节或者变长字符的序列。
  5. 在使用string类时,必须包含#Include头文件以及using namespace std;

二、string类的常用接口

1.string类对象的常见构造

函数名称功能说明
string()构造空的string类对象,即空字符串
string(const char* s)用C-string来构造string类对象
string(size_t n, char c)string类对象中包含n个字符c
string(cosnt string& s)拷贝构造函数

在这里插入图片描述

实例:

int main()
{
	string s1;
	string s2("hello world");
	string s3 = "hello world";
	for (size_t i = 0; i < s2.size(); i++)
	{
		s2[i]++;
	}
	cout << s2 << endl;//结果:ifmmp!xpsme
	for (size_t i = 0; i < s2.size(); i++)
	{
		cout << s3[i] << " "; //结果:h e l l o   w o r l d
	}
	cout << endl;

	string s4(s3, 6, 3); //第6个字符开始,取3个字符
	cout << s4 << endl; //结果:wor

	string s5(s3, 6, 13);//有多少取多少
	cout << s5 << endl;//结果:world

	string s6(s3, 6);
	cout << s6 << endl;//结果:world

	string s7("hello world", 5);
	cout << s7 << endl;//结果:hello

	string s8(10, '*');
	cout << s8 << endl;//结果:**********
	system("pause");
	return 0;
}

2.string类对象的容量操作

函数名称功能说明
size()返回字符串有效长度
length返回字符串有效长度
capacity返回空间总大小
empty检测字符串释放为空串,是返回true,否则返回false
clear清空有效字符
reserve为字符串预留空间
resize将有效字符的个数改成n个,多出的空间用字符c填充

测试string容量相关的接口
size / clear / resize

int main()
{
	// 注意:string类对象支持直接用cin和cout进行输入和输出
	string s1("hello world");
	cout << s1.size() << endl;//结果:11
	cout << s1.length() << endl;//结果:11
	cout << s1.max_size() << endl;//结果:2147483647
	cout << s1.capacity() << endl;//结果:15

	// 将s1中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
	s1.clear();
	cout << s1.size() << endl;//结果:0
	cout << s1.capacity() << endl;//结果:15

	// 将s中有效字符个数增加到10个,多出位置用'a'进行填充
	s1.resize(10, 'a');
	cout << s1.size() << endl;//结果:10
	cout << s1.capacity() << endl;//结果:15

	// 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
	//"aaaaaaaaaa\0\0\0\0\0"
	//此时s1中有效字符个数已经增加到15个
	s1.resize(15);
	cout << s1.size() << endl;//结果:15
	cout << s1.capacity() << endl;//结果:15

	// 将s中有效字符个数缩小到5个
	s1.resize(5);
	cout << s1.size() << endl;//结果:5
	cout << s1.capacity() << endl;//结果:15
	system("pause");
	return 0;
}

测试reserve / resize

int main()
{
	// 测试reserve是否会改变string中有效元素个数
	string s1("hello world");
	s1.reserve(100); //扩容
	cout << s1.size() << endl;//结果:11
	cout << s1.capacity() << endl;//结果:111

	// 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
	s1.reserve(50);
	cout << s1.size() << endl; //结果:11
	cout << s1.capacity() << endl;//结果:111

	// 测试resize是否会改变string中有效元素个数
	string s2("hello world");
	s2.resize(100);//扩容+初始化:s2.resize(100, 'x');
	cout << s2.size() << endl;//结果:100
	cout << s2.capacity() << endl;//结果:111
	system("pause");
	return 0;
}

观察扩容情况,如下:

int main()
{
	string s1;
	cout << sizeof(s1) << endl;//结果:28
	size_t sz = s1.capacity();
	cout << "making s grow:\n";
	cout << "capacity changed: " << sz << '\n'; //结果:capacity changed : 15
	for (int i = 0; i < 100; i++)
	{
		s1.push_back('c');
		if (sz != s1.capacity())
		{
			sz = s1.capacity();
			cout << "capacity changed: " << sz << '\n'; //结果:capacity changed : 31
				                                        //      capacity changed : 47
			                                            //      capacity changed : 70
				                                        //      capacity changed : 105
		}
	}
	system("pause");
	return 0;
}

可以利用reserve提高插入数据的效率,避免增容带来的开销

构建vector时,如果提前已经知道string中大概要放多少个元素,可以提前将string中空间设置好,代码如下:

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

运行结果:
在这里插入图片描述
注意:

  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的底层空间总大小时,reserve不会改变容量大小。

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

函数名称功能说明
operator[]返回pos位置的字符,const string类对象调用
begin+endbegin获取第一个字符的迭代器+end获取最后一个字符下一个位置的迭代器
rbegin + rendrbegin获取最后一个字符的迭代器 + end获取第一个字符上一个位置的迭代器

string的遍历,代码如下:

int main()
{
	string s1("hello world");
	const string s2("Hello World");
	cout << s1 << " " << s2 << endl;//结果:hello world Hello World
	cout << s1[0] << " " << s2[0] << endl;//结果:h H
	s1[0] = 'H';
	cout << s1 << endl;//结果:Hello world
	// s2[0] = 'h'; //代码编译失败,因为const类型对象不能修改
	system("pause");
	return 0;
}

三种遍历方式,代码如下:

int main()
{
	string s1("hello world");
	
	// 1. for+operator[]
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i]; //结果:hello world
	}
	cout << endl;

	// 2. 迭代器
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it; //结果:hello world
		it++;
	}
	cout << endl;

	// 3.范围for
	for (auto ch : s1)
	{
		cout << ch;
	}
	cout << endl;//结果:hello world
	system("pause");
	return 0;
}

反向迭代器,代码如下:

int main()
{
	string s1("hello world");
	string::reverse_iterator it = s1.rbegin();
	while (it != s1.rend())
	{
		cout << *it; //结果:dlrow olleh
		it++;
	}
	cout << endl;

	system("pause");
	return 0;
}

4.string类对象的修改操作

函数名称功能说明
push_back在字符串后尾插入字符c
append在字符串后追加一个字符串
operator+=在字符串后追加字符串str
c_str返回C格式字符串
find+npos从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr在str中从pos位置开始,截取n个字符,然后将其返回

测试插入(拼接)方式:push_back append operator+=,代码如下:

int main()
{
	string s1("hello world");
	s1.push_back(' ');//在s1后插入空格
	s1.append("hello"); //在str后追加一个字符"hello"
	s1 += 'w'; //在str后追加一个字符'b'
	s1 += "orld"; //在str后追加一个字符串"it"
	cout << s1 << endl;//结果:hello world helloworld
	cout << s1.c_str() << endl;//结果:hello world helloworld
	system("pause");
	return 0;
}

测试正向和反向查找:find() + rfind(),代码如下:

int main()
{
	// 用find获取file1的后缀
	string file1("string.cpp");
	size_t pos1 = file1.find('.');
	if (pos1 != string::npos)//  npos是string里面的一个静态成员变量
		                    //  static const size_t npos = -1;
	{
		string suffix1 = file1.substr(pos1, file1.size() - pos1);
		// 等价于 string suffix = file1.substr(pos1);
		cout << suffix1 << endl;//结果:.cpp
	}

	// 用rfind获取file2的最后一个后缀
	string file2("sting.cpp.tar.zip");
	size_t pos2 = file2.rfind('.');
	if (pos2 != string::npos)
	{
		string suffix2 = file2.substr(pos2);
		cout << suffix2 << endl;//结果:.zip
	}

	// 取出url中的域名
	string url("http://www.cplusplus.com/reference/string/string/find/");
	cout << url << endl;//结果:http://www.cplusplus.com/reference/string/string/find/
	size_t start = url.find("://");
	if (start == string::npos)
	{
		cout << "invalid url" << endl;
		return 0;
	}
	start += 3;
	size_t finish = url.find('/', start);
	string address = url.substr(start, finish - start);
	cout << address << endl;//结果:www.cplusplus.com

	// 删除url的协议前缀
	size_t pos = url.find("://");
	url.erase(0, pos + 3);
	cout << url << endl;//结果:www.cplusplus.com/reference/string/string/find/
	system("pause");
	return 0;
}

实例,把空格转换成%20,代码如下:

int main()
{
	string s1("hello world i love you");
	size_t num = 0;
	for (auto ch : s1)
	{
		if (ch == ' ')
			num++;
	}
	//提前开空间,避免replace时扩容
	s1.reserve(s1.size() + 2 * num);

	size_t pos = s1.find(' ');
	while (pos != string::npos)
	{
		s1.replace(pos, 1, "%20");
		pos = s1.find(' ');//等价于pos=s1.find(' ',pos+3); 提高效率
	}
	cout << s1 << endl;//结果:hello%20world%20i%20love%20you
	system("pause");
	return 0;
}

优化,代码如下:

int main()
{
	string s1("hello world i love you");
	string newstr;
	for (auto ch : s1)
	{
		if (ch != ' ')
			newstr += ch;
		else
			newstr += "%20";
	}
	s1 = newstr;//修改原字符串
	cout << s1 << endl;//结果:hello%20world%20i%20love%20you
	system("pause");
	return 0;
}

注意:

  1. 在string尾部追加字符时,s.push_back© / s.append(1,c) / s+=‘c’ 三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

5.string类非成员函数

函数名称功能说明
operator+尽量少用,因为传值返回,导致深拷贝效率低
operator>>输入运算符重载
operator<<输出运算符重载
getling获取一行字符串
relational operator大小比较

6.vs和g++下string结构的说明

注意:下述结构是在32位平台下进行验证,32位平台下指针占4个字节。

  • vs下string的结构
    string总共占28个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义string中字符串的存储空间:
    1、当字符串长度小于16时,使用内部固定的字符数组来存放
    2、当字符串长度等于16时,从对上开辟空间
union _Bxty
{
	value_type _Buf[_BUF_SIZE];
	pointer _Ptr;
	char _Alias[_BUF_SIZE];
} _Bx;

这种设计也有一定道理的,大多数情况下字符串的长度都小于16,那string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。
其次:还有一个size_t字段保存字符串长度,应该size_t字段保存从堆上开辟空间总的容量
最后:还有一个指针做一些其他事情
所以共占用16+4+4+4=28个字节
在这里插入图片描述

  • g++下string的结构
    g++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段:
    1、空间总大小
    2、字符串有效长度
    3、引用计数
struct _Rep_base
{
	size_type _M_length;
	size_type _M_capacity;
	_Atomic_word _M_refcount;
};

4、指向堆空间的指针,用来存储字符串。

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

柒个葫芦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值