C++ 中的 std::string 类

2,441 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

C++ 在其定义中有一种将字符序列表示为 class 对象的方法。这个类叫做 std::string。String 类将字符存储为具有允许访问单字节字符的功能的字节序列。 

std:: 字符串与字符数组

  • 字符数组只是一个可以由空字符终止的字符数组。字符串是定义表示为字符流的对象

  • 字符数组的大小必须静态分配,如果需要,不能在运行时分配更多内存。在字符数组的情况下,未使用的分配内存被浪费。在字符串的情况下,内存是动态分配的。可以在运行时按需分配更多内存。由于没有预先分配内存,因此不会浪费任何内存

  • 如果是字符数组,则存在数组衰减的威胁。由于字符串表示为对象,因此不会发生数组衰减

  • 实现字符数组是快比的std :: string。与实现相比,字符串比字符数组

  • 字符数组不提供很多内置函数来操作字符串。String 类定义了许多允许对字符串进行多种操作的功能

字符串操作

输入函数
1. getline()  :- 该函数用于在对象内存中存储用户输入的字符流
2. push_back()  :- 该函数用于在字符串的末尾 输入一个字符。3. pop_back()  :- 从 C++11 引入(用于字符串),该函数用于删除字符串中的最后一个字符

#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
	string str;
	getline(cin,str);
	cout << "The initial string is : ";
	cout << str << endl;
	str.push_back('s');
	cout << "The string after push_back operation is : ";
	cout << str << endl;
	str.pop_back();
	cout << "The string after pop_back operation is : ";
	cout << str << endl;
	return 0;
}

输入:

juejiner

输出:

The initial string is : juejiner
The string after push_back operation is : juejiners
The string after pop_back operation is : juejiner

容量函数
4. capacity()  :- 该函数返回分配给字符串的容量,该容量可以等于或大于字符串的大小。分配了额外的空间,以便在将新字符添加到字符串时,可以有效地完成操作
5. resize()  :- 这个函数改变字符串的大小,大小可以增加或减少。
6.length()  :-此函数求字符串的长度
7.shrink_to_fit()  :- 此函数减少字符串的容量,使其等于字符串的最小容量。这个操作是****如果我们确定不需要进一步添加字符,则有助于节省额外的内存

#include<iostream>
#include<string> 
using namespace std;
int main()
{
	string str = "juejin is for juejiners";
	cout << "The initial string is : ";
	cout << str << endl;
	str.resize(13);
	cout << "The string after resize operation is : ";
	cout << str << endl;
	cout << "The capacity of string is : ";
	cout << str.capacity() << endl;
	cout<<"The length of the string is :"<<str.length()<<endl;
	str.shrink_to_fit();
	cout << "The new capacity after shrinking is : ";
	cout << str.capacity() << endl;
	return 0;
}

输出

The initial string is : juejin is for juejiners
The string after resize operation is : juejiners
The capacity of string is : 23
The length of the string is :9
The new capacity after shrinking is : 9

迭代器函数
8. begin()  :- 这个函数返回一个迭代器到字符串的开头
9.端() :-该函数返回一个迭代结束的字符串。
10. rbegin()  :- 该函数返回一个指向字符串末尾反向迭代器11.rend()  :- 这个函数返回一个指向字符串开头反向迭代器

#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
	string str = "juejin";
	std::string::iterator it;
	std::string::reverse_iterator it1;
	cout << "The string using forward iterators is : ";
	for (it=str.begin(); it!=str.end(); it++)
	cout << *it;
	cout << endl;
	cout << "The reverse string using reverse iterators is : ";
	for (it1=str.rbegin(); it1!=str.rend(); it1++)
	cout << *it1;
	cout << endl;
	return 0;
}

输出

The string using forward iterators is : juejin
The reverse string using reverse iterators is : nijeuj

操作函数
12. copy(“char array”, len, pos)  :- 该函数复制其参数中提到的目标字符数组中的子字符串**。它需要 3 个参数,目标字符数组,要复制的长度和开始复制的字符串中的起始位置。
13. swap()  :- 该函数将一个字符串与另一个字符串交换