c++ string类的常用方法

c++ string类的常用方法


2024年5月16日发(作者:)

c++ string类的常用方法

一、C++ string类的常用方法

1、string类的构造函数

string() // 构造空串

string(const char* s) // 把null结尾的字符串s拷贝到字

符串中

string(const string& str) // 拷贝构造函数,复制str到

此串

string(char c, int n) // 用n个字符c构造串

string(const char* s, int n) // 拷贝字符数组中前n个字

2、string类的成员函数

2.1 长度控制函数

int size() const; // 返回字符串的长度

int length() const; // 返回字符串的长度,等价于

size()

void resize(int n, char c); // 改变字符串长度,如果n

大于原来的长度,用字符c来填充

2.2 内容操作函数

string& operator=(const char* s); // 赋值,把s的内容

复制到字符串中

string& assign(const char* s); // 赋值,把s的内容

- 1 -

复制到字符串中

string& append(const char* s); // 把字符串s添加到

串尾

string& append(const char* s, int n); // 把s前n个字符

添加到串尾

string& insert(int p0, const char* s); // 在p0位置上

插入字符串s

string& erase(int p0, int n); // 删除p0开始,

n个字符

int find(const char* s, int pos=0); // 在

pos之后查找子串s,返回子串s在原串中的起始位置

int find(char c, int pos=0); // 从

pos开始查找字符c,返回字符c在原串中的位置

int rfind(const char* substr,int pos=npos); // 从

pos开始向前查找子串substr,返回子串substr在原串中的起始位

int rfind(char c, int pos=npos); // 从

pos开始向前查找字符c,返回字符c在原串中的位置

string substr(int pos, int n); // 返回串pos

位置开始,长度为n的子串

2.3 字符串比较函数

int compare(const char* s); // 比较原串和

- 2 -

s

int compare(int p0, int n, const char* s); // 比较串中

p0开始,n个字符的子串和s

2.4 数据访问函数

char& operator[](int i); // 返回串中第

i个字符的引用

const char& operator[](int i) const; // 返回串中第

i个字符的引用

const char* c_str() const; // 返回字符串以

null结尾的字符串

2.5 输入输出函数

ostream& operator<<(ostream& os, const string& str); //

输出字符串

istream& operator>>(istream& is, string& str); //

输入字符串。

- 3 -


发布者:admin,转转请注明出处:http://www.yc00.com/web/1715798547a2673329.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信