标准库string总结2

sbustr操作

string substr(int pos=0, int n=npos) const;    //返回由pos开始的n个字符组成的子字符串
string s("Hello World");
string s1=s.substr(0,5); //s1=Hello
string s2=s.substr(6); //s2=World
string s3=s.substr(6,11); //s3 = World
string s4=s.substr(12); //抛出一个异常out_of_range

compare函数

int compare(const string &s) const;  //与字符串s比较
int compare(const char *s) const;   //与字符串s比较
string s1("hello");
string s2("Hello");
s1.compare(s2);
//当s1大于s2时,返回一个等于零的数;
//当s1等于s2时,返回0;
//当s1小于s2时,返回一个小于零的数;
//比较时参考字典顺序,排越前面的越小。大写的A比小写的a小。
//通过测试得到,其实返回值是两个字符串所对应第一对不同字符的ASCII码的差值

string查找函数

s.find(args); //查找s中args第一次出现的位置
s.rfind(args); //反向查找,查找s中args最后一次出现的位置
s.find_first_of(args); //在s中查找args中任何一个字符第一次出现的位置
s.find_last_of(args); //在s中查找args中任何一个字符最后一次出现的位置
s.find_first_not_of(args); //在s中查找第一个不在args中的字符
s.find_last_not_of(args); //在s中查找最后一个不在args中的字符

返回值:
每个搜索返回一个string::size_type值,表示匹配发生位置的下标;如果搜索失败,则返回一个名为string::npos,其值为-1。

  • string搜索函数返回string::size_type值,该类型是一个unsigned类型。所以用int表示返回值,其实并不满意。

string查找还可以指定某个位置起查找:

int find(char c,int pos=0) const;  //从pos开始查找字符c在当前字符串的位置 
int find(const char *s, int pos=0) const;  //从pos开始查找字符串s在当前字符串的位置
int find(const string &s, int pos=0) const;  //从pos开始查找字符串s在当前字符串中的位置
//find函数如果查找不到,就返回npos
int rfind(char c, int pos=npos) const;   //从pos开始从后向前查找字符c在当前字符串中的位置 
int rfind(const char *s, int pos=npos) const;
int rfind(const string &s, int pos=npos) const;
//rfind是反向查找的意思,如果查找不到, 返回npos

string替换函数

string &replace(int pos, int n, const char *s);//删除从pos开始的n个字符,然后在pos处插入串s
string &replace(int pos, int n, const string &s);  //删除从pos开始的n个字符,然后在pos处插入串s

replace()函数在替换字符或字符串时,不必与要替换的字符串的长度相同,可以长也可以短。

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s="you are good,you are happy!";
    auto k=s.find("you");
    while(k!=string::npos)
    {
        s.replace(k,3,"we");
        k=s.find("you",k);
    }
    //替换后输出
    cout<<s<<endl; //we are good,we are happy!
    return 0;
}

string区间删除与插入

string &insert(int pos, const char *s);
string &insert(int pos, const string &s);
//前两个函数在pos位置插入字符串s
string &insert(int pos, int n, char c);  //在pos位置 插入n个字符c

string &erase(int pos=0, int n=npos);  //删除pos开始的n个字符,返回修改后的字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值