STL——string

以下代码配合该大佬博客食用

#include <iostream>
#include<bits/stdc++.h>

using namespace std;
void test1()
{
    string a;
    string b("asdf");
    string c="adfasdf";
    string d=c;
    string e(3,'e');
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;
    cout<<d<<endl;
    cout<<e<<endl;
}
void test2()
{
    //chan
    string a="absfasdfa";
    for(int i=0;i<a.length();i++)
        cout<<a[i]<<" ";
    cout<<endl;
    //迭代器
    string::iterator it;
    for(it=a.begin();it!=a.end();++it)
        cout<<*it<<" ";
    cout<<endl;
}
void test3()
{
    string s1="asdfadsf";
    //将string 转换成char*/
    printf("%s\n",s1.c_str());

    /*将string拷贝到char*指向的内存空间*/
    char buf[128]={0};
    s1.copy(buf,5,2);       //从2开始复制5个
    cout<<buf<<endl;



}

void test4()
{
    //比较函数:按照字典序 一位一位向下比较
    string a="adsf";
    string b="df";
    cout<<(a<b)<<endl;
    cout<<a.compare(b)<<endl;

    string c="1000";
    string d="20";
    cout<<(c<d)<<endl;
    cout<<c.compare(d)<<endl;
}
void test5()
{
    string a="aaaa";
    string b("bbbb");
    a+=b;
    cout<<a<<endl;

    string c="cccc";
    string d="dddd";
    c.append(d);
    cout<<c<<endl;

}
void test6()
{
    //(1)子串
    //返回由pos开始的n个字符
    string a="abcdecg";
    string b=a.substr(2,3);
    cout<<b<<endl;

    //(2)find()
    /*从pos开始查找字符c在当前字符串的位置*/
    cout<<a.find('c',0)<<endl;
    cout<<a.find('c',3)<<endl;
    cout<<a.find('i',0)<<endl;

    /*从pos开始查找字符串s在当前字符串的位置*/
    cout<<a.find("dec",0)<<endl;
    cout<<a.find("fds",0)<<endl;

    //rfind 从后向前找
    cout<<a.rfind('c',4)<<endl;

    //(3)替换
    //删掉从pos开始的n个字符,并且在pos处插入字符串s
    string d="aaaaaa";
    d.replace(3,4,"bbbbbb");
    cout<<d<<endl;

    //swap(string &s2) 交换当前字符串与s2的值
    string e="asdfa";
    d.swap(e);
    cout<<d<<endl;


}
void test7()
{
    string a="aaaaaaaaaa";
    a.insert(3,"bbbbbbbbbb");
    cout<<a<<endl;

    a.insert(5,3,'c');
    cout<<a<<endl;

    a.erase(0,10);
    cout<<a<<endl;
}
int main()
{
    //1
    /*初始化---构造参数*/
   // test1();

    //2
    /*存取字符*/
    //test2();

    //3
    /*和char*类型的转换*/
    //test3();

    //4
    /*比较操作*/
    //test4();

    //5
    //字符串连接
    //test5();


    //6
    //查找和替换
    //test6();

    //7
    //删除与插入
    //test7();


    //cout << "Hello world!" << endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值