两分钟带你搞懂string里面的基本函数使用方法,确定不来看看

直接上代码

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
    cout<<"----------find方法--------------"<<endl;
    string str="I'm a boy!!!";
    string s="boy";

    //find在str中寻找子字符串,找到了返回在str中的下标位置,找不到返回-1
    int p=str.find("tytu");
    int r=str.find('m');
    int q=str.find(s);
    cout<<"p: "<<p<<" r: "<<r<<" "<<"q:"<<q<<endl<<endl;

    cout<<endl<<"----------erase方法--------------"<<endl;
    //erase函数删除子字符串
    string a;
    a=str.erase(5);           //删除从下标5开始的字符串,str自身也会改变
    string b=str.erase(2,2);  //删除从下标2开始的两个字符
    //str修改了两次,每次erase都对本身进行了修改
    cout<<" str: "<<str<<endl<<" a: "<<a<<endl<<" b: "<<b<<endl<<endl;

    cout<<endl<<"----------substr方法--------------"<<endl;
    //substr求从哪个位置开始的子字符串
    string ss="hello,word";
    string ss1=ss.substr(3);  //从下标3开始的字符串
    string ss2=ss.substr(2,3); //从下标2开始的三个字符;
    cout<<"ss: "<<ss<<" ss1: "<<ss1<<" ss2 "<<ss2<<endl<<endl;

    cout<<endl<<"----------insert方法--------------"<<endl;
    //insert为插入函数
    string c=",";
    cout<<c<<endl;
    c.insert(0,"heo");     //在第0为之前插入字符串hero
    cout<<c<<endl;
    c.insert(4,"world",2); //在第下标为4前插入word的前两个字符
    cout<<c<<endl;
    c.insert(2,2,'l');     //在下标2之前插入字符两次
    cout<<c<<endl;
    c.insert(c.end(),'r'); //在字符串c最后插入字符
    cout<<c<<endl;
    c+="ld!";              //加法直接运算,连接
    cout<<c<<endl<<endl;

    cout<<endl<<"----------replace方法--------------"<<endl;
    //replace函数为替换

    //将所有“you”替换成“we”,                       poj3981
    string str1 = "I love you and you love me";
    while(str1.find("you")!=-1)
    {
        str1.replace(str1.find("you"),3,"we");
    }
    cout<<str1<<endl;

    string d="abcsdfdf";
    d=d.replace(d.find("s"),3,"@");  //从第几个位置开始3个字符换为一个@
    cout<<d<<endl;
//
//    string xx="you my you!!!";
//    getline(cin,xx);  //输入字符串,以回车结束
//    int asn;
//    while((asn=xx.find("you"))!=-1)
//    {
//        xx.replace(asn,3,"we");
//    }
//    cout<<xx<<endl;

    cout<<endl<<"----------compare方法--------------"<<endl;
    //比较
    string cc1="123",cc2="124";
    int t=cc1.compare(cc2);  //相同返回0,cc1大返回1,cc2大返回-1
    cout<<t<<endl;

    cout<<endl<<"----------reverse方法--------------"<<endl;
    //反转
    string zz="123123";
    //反转全部
    reverse(zz.begin(),zz.end());
    cout<<zz<<endl;

    string za="123123";
    //反转部分
    reverse(za.begin()+3,za.begin()+za.length());
    cout<<za;
    return 0;
}

结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值