C++ string 详解:STL 字符串容器的使用技巧
STL 简介
STL(Standard Template Library,标准模板库)是 C++ 标准库的重要组成部分,不仅是一个可复用的组件库,而且是一个包罗数据结构与算法的软件框架。
STL 的版本历史
- HP 版本:由 Alexander Stepanov、Meng Lee 在惠普实验室完成,开源且允许任意运用、拷贝、修改。是所有 STL 实现版本的始祖。
- P.J. 版本:由 P. J. Plauger 开发,继承自 HP 版本,被 Windows Visual C++ 采用。不可公开或修改,可读性较低。
- RW 版本:由 Rouge Wage 公司开发,继承自 HP 版本,被 C++ Builder 采用。不可公开或修改,可读性一般。
- SGI 版本:由 Silicon Graphics Computer Systems, Inc 开发,继承自 HP 版本,被 GCC (Linux) 采用。可移植性好,可公开、修改甚至贩卖,命名和编程风格阅读性非常高。
String 类概述
C 语言中的字符串
C 语言中,字符串是以 '\0' 结尾的一些字符的集合。C 标准库提供了一些 str 系列的库函数,但这些库函数与字符串是分离开的,不太符合 OOP 的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
OOP 思想
OOP(Object-Oriented Programming)即面向对象编程,核心是将程序中的数据和操作数据的方法封装成对象,通过对象之间的交互来完成程序功能。string 类正是基于此设计,提供了更安全便捷的字符串处理方式。
string 常见构造方式
以下是 string 类的九种常见构造方法示例:
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
using namespace std;
int main() {
// 1. 空构造函数:创建一个空字符串
string s1;
cout << "s1 (空构造): \"" << s1 << "\" (长度:" << s1.size() << ")" << endl;
// 2. 字符串常量构造:用 C 风格字符串(const char*)初始化
string s2("12345");
cout << "s2 (字符串常量构造): \"" << s2 << "\" (长度:" << s2.() << << endl;
;
cout << << s3 << << s() << << endl;
;
cout << << s4 << << s() << << endl;
;
cout << << s4_extend << << s4_extend.() << << endl;
;
cout << << s5 << << s() << << endl;
;
cout << << s5_extend << << s5_extend.() << << endl;
;
cout << << s6 << << s() << << endl;
;
cout << << s7 << << s() << << endl;
;
cout << << s8 << << s() << << endl;
string s9{, , , , };
cout << << s9 << << s() << << endl;
;
}


