string的基本操作
一.与C语言中字符串的区别
C语言中的字符串是以’\0’为结束标志的字符的数组,但字符串函数与字符串是分离的,这与OOP(面向对象编程)的思想不符,所以C++提供了支持自动扩容且用类域封装的——string类
二.标准库中的string
官方文档中对string类的介绍如下:
String class
Strings are objects that represent sequences of characters.
( 字符串是表示字符序列的类)
The standard string class provides support for such objects with an interface similar to that of a standard container of bytes, but adding features specifically designed to operate with strings of single-byte characters.
( 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。)
The string class is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type, with its default char_traits and allocator types (see basic_string for more info on the template).
(string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。)
Note that this class handles bytes independently of the encoding used: If used to handle sequences of multi-byte or variable-length characters (such as UTF-8), all members of this class (such as length or size), as well as its iterators, will still operate in terms of bytes (not actual encoded characters).
(注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。)
三.string中常用接口的介绍
1.string中常用的构造函数
constructor函数 | 功能说明 |
---|---|
string() | 默认构造,构造空字符串的string类 |
string (const string& str) (重点) | 用一个string对象来构造新的string对象(拷贝构造) |
string (const string& str, size_t pos, size_t len = npos) | 用一个string对象pos位置开始的len个字符构造,如果len太大或者len==npos就直到末尾 |
string (const char* s)(重点) | 用C-string来构造string类对象 |
string (const char* s, size_t n) | 用C-string的前n个字符构造 |
string (size_t n, char c) | 用n个c字符构造初始化 |
template <class InputIterator>string (InputIterator first, InputIterator last)(重点) | 用一段迭代器区间构造 |
测试用例:
int main()
{
string s1;
string s2("hello world");
string s3(s2);
string s4("hello world", 5);
string s5(5, 'x');
cout << "s1:" <&