string 的一些字符串操作函数

1.find查找函数
函数原型:

size_t find ( const string& str, size_t pos = 0 ) const; 
size_t find ( const char* s, size_t pos, size_t n ) const; 
size_t find ( const char* s, size_t pos = 0 ) const; 
size_t find ( char c, size_t pos = 0 ) const;

参数说明:pos查找起始位置 n待查找字符串的前n个字符

find函数在找不到指定值得情况下会返回string::npos

使用样例:

string str1("the usage of find can you use it");

string str2("the");

上面定义出了两个字符串;

str1.find(str2); // 从串str1中查找时str2,返回str2中首个字符在str1中的地址

str1.find(str2,5); // 从str1的第5个字符开始查找str2,成功返回str2的首字母的下标位置

str1.find(“usage”); // 如果usage在str1中查找到,返回u在str1中的位置

str1.find(“o”); // 查找字符o并返回地址

str1.find(“of big”,2,2); // 从str1中的第二个字符开始查找of big的前两个字符

2.函数find_first_of()和 find_last_of() 执行简单的模式匹配

int find_first_of(char c, int start = 0):
查找字符串中第1个出现的c,由位置start开始。
如果有匹配,则返回匹配位置;否则,返回-1.默认情况下,start为0,函数搜索
整个字符串。
int find_last_of(char c,int end):
查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1.
该搜索在字符末尾查找匹配,所以没有提供起始位置。
同样还可以有find_first_not_of等函数,函数名顾名思义,就是找第一个不是我要求字符的位置,注意,输出的结果总是下标,下标是从0开始的。

3. string substr(int start=0,int count= -1);

参数分别是开始,长度。
从起始位置开始复制字符串中的count 个字符,并返回这些字符作为子串。
如果字符串尾部小于count字符或者count 为-1,则字符串尾停止复制。
如果不使用参数调用只包括位置start,则substr()返回从位置开始到字符串尾部的子串。

4.void insert(int statr,const string& s):

字符连接(+、+=)是在字符串尾添加字符串。insert()函数扩展了这个能力,
允许在任意位置添加字符串。为了从字符串。
将子串s放入字符串中,起始于位置start。插入操作增加了原始字符串的长度。
string &insert(int p0, const char *s, int n);——在p0位置插入字符串s的前n个字符
string &insert(int p0,const string &s);——在p0位置插入字符串s
string &insert(int p0,const string &s, int pos, int n);——在p0位置插入字符串s从pos开始的连续n个字符
string &insert(int p0, int n, char c);//在p0处插入n个字符c
iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置
void insert(iterator it, const_iterator first, const_iteratorlast);//在it处插入从first开始至last-1的所有字符
void insert(iterator it, int n, char c);//在it处插入n个字符c

5.erase()函数

iterator erase(iterator first, iterator last);//删除[first,last)之间的所有字符,返回删除后迭代器的位置
iterator erase(iterator it);//删除it指向的字符,返回删除后迭代器的位置
string &erase(int pos = 0, int n = npos);//删除pos开始的n个字符,返回修改后的字符串

6.c_str()返回c语言风格字符串的地址。

作者:杨美人!
原文:https://blog.csdn.net/qq_40679299/article/details/80240870

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值