一、C++ 标准库中的string类
string类的文档介绍
首先string并不是STL中的,而是一个类string比STL出现的早
从上面可以看出string是从一个类模板中实例化出来的一个对象
在使用string类是必须要包头文件#include< string >
又因为是std中的类,所以要using namespace std; 将std开放,否则就要在使用时加上std::
//开放std类域
string s1;
//未开放,需要表明是哪个类域的
std::string s2;
二、string类常用接口
只是常用的,其他的只做了解,在需要时能想起来有,并且能查就行,并且下面的都只是C++98版本的,C++11以及往后新加的并没有涉及
1、string类的常见构造(constructor)
constructor(构造)----------链接
constructor函数名称(重点掌握) | 功能说明 |
---|---|
string( ) | 构造空string类对象,即空字符串 |
string (const char* s) | 用C-string来构造string类对象 |
string (size_t n, char c) | string对象中包含 n 个字符 c |
string (const string& str) | 拷贝构造函数 |
#include<iostream>
#include<string>
using namespace std;int main()
{//default (1) string();string s1;cout << "s1 : " << s1 << endl;//from C-string (4) string(const char* s)string s2("123456");cout << "s2 : " << s2 << endl;//copy (2) string(const string & str)string s3(s2);cout << "s3 : " << s3 << endl;//substring (3) string(const string & str, size_t pos, size_t len = npos)string s4(s2, 2, 3);cout << "s4 : " << s4 << endl;//因为此函数不管后面的len填多少到字符串末尾就会结束//上面函数参数 size_t len有缺省值npos,就是如果不填会默认填最大值string s5(s2, 1);cout << "s5 : " << s5 << endl;//from sequence (5) string(const char* s, size_t n)string s6("1111111", 4);cout << "s6 : " << s6 << endl;//fill (6) string(size_t n, char c)string s7(7, 'c');cout << "s7 : " << s7 << endl;return 0;
}
2、string 类对象的容量操作
3、string类对象的访问及遍历操作
函数名称 | 功能说明 |
---|---|
operator[ ] | 返回pos位置的字符,const string类对象调用 |
– | – |
<1>operator[ ]
#include<iostream>
#include<string>
using namespace std;int main()
{string s1("1234567");cout << s1 << endl;s1[2] = '4';cout << s1 << endl;const string s2("111111111");cout << s2[2] << endl;return 0;
}