c++头文件string函数的用法

目录

前言:

字符串截取

字符串插入与替换

 字符串区间删除

 字符串排序与相加和查找

如后续需文字描述,,请评论区告诉我,我看到后会进行添加一些文字描述。


前言:

因本人女朋友在学习c++过程中在一些知识网页上学了string但是无法实现,发现别人上传的string函数用法有些错误,特写此文章以防误人子弟,主要介绍了string常见用法,其中包括:字符串截取,字符串区间删除,字符串排序与相加和查找,字符串插入与替换,因为比较基础特此便少些文字描述~(就是偷懒!~,但是绝对保证语法正确)

字符串截取

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
    s="0123456789";
    a1=s.substr(5,2);
    cout<<"字符串s"<<s<<endl;
    cout<<"获得s在第5个位置长度为2的字符串:"<<a1<<endl;

       return 0;
}

字符串插入与替换

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
    s="0123456789";
    s.insert(s.begin()+5,'s');
    cout<<s;
    return 0;
}

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
    s="0123456789";
    s.replace(5,0,"aaa");
    cout<<"s在第5个位置添加“aaa”这个字符串:"<<s<<endl;
    string s1="0123456789";
    s1.replace(5,2,"aaa");
    cout<<"s1在第5个位置到第7个位置换成“aaa”这个字符串:"<<s1<<endl;
    return 0;
}

 字符串区间删除

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string s,a1;
int main(){
    s="0123456789";
    s.erase(5,2);
    cout<<"字符串s:"<<s<<endl;
    cout<<"删掉s在第5个位置长度为2的字符串“56”:"<<s<<endl;

       return 0;
}

 字符串排序与相加和查找

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
string s,s1;
int main(){
    s="01234";s1="56789";
    string S;
    S=s1+s;
    cout<<"字符串相加"<<S<<endl;
    sort(S.begin(),S.end());
    cout<<"字符串排序"<<S<<endl;
    int a56=S.find("56");
    int a99=S.find("99");
    cout<<"字符串查找,如果能查找到返回查找到的第一个字符下标:"<<a56<<endl;
    cout<<"查找不到返回-1:"<<a99<<endl;
    cout<<"查找既可以是字符也可以是字符串"<<endl;
       return 0;
}

如后续需文字描述,,请评论区告诉我,我看到后会进行添加一些文字描述。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

善程序员文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值