C++ 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中常用的构造函数

Alt

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:" <&
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值