c++ string类型使用

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

//字符串类初始化
void main21()
{
    string a1="aaa";
    string a2("bbb");
    string a3(3,'c');
    cout<<a1<<a2<<a3<<endl;
}
//string的遍历
void main22()
{
    string a1="abcdefg";
    //数组方式
    int i=0;
    for(i=0;i<a1.length();i++)
    {
        cout<<a1[i]<<" ";
    }
    cout<<"\n";
    //迭代器方式
    for(string::iterator it=a1.begin();it!=a1.end();it++)
    {
        cout<<*it<<" ";
    }
    cout<<endl;
    //通过 at()  
    //at()可以抛异常
    try
    {
            for(i=0;i<a1.length()+3;i++)
        {
                    cout<<a1.at(i)<<" ";
        }

    }
    catch(...)
    {
        cout<<"error in try"<<endl;
    }
}

//字符指针和string类的转换
void main23()
{
    //指针 转 string
    string s1= "aaa";
    //string 转 指针
    const char *p=s1.c_str(); //string.c_str()暴露类中成员 char* 的首地址;
    cout<<p<<endl;  
    //string拷贝到 指针指向的内存空间
    char buf[1024]="bbbbb";
    s1.copy(buf,3,0); //从0号开始,拷贝3个字符到buf.buf并不是c风格字符串.*(p+5)='/0'; //要手动加上结束符
    cout<<buf<<endl;
}
//字符串连接
void main24()
{

    string a1="aaa";
    string a2="bbb";
    //使用+号连接
    string a3=a1+a2;
    cout<<"a3="<<a3<<endl;
    //使用 string.append(obj)
    string a4="ccc";
    a3.append(a4);
    cout<<"a3="<<a3<<endl;
}
//string 的区间删除 和插入
void main25()
{
    string a1 = "hello1 hello2 hello3";
    string::iterator it = find(a1.begin(), a1.end(), 'l');
    if (it != a1.end())
        a1.erase(it);
    cout << a1 << endl;
    //整个删除
    a1.erase(a1.begin(), a1.end());
    cout << a1 << endl;
    cout << a1.length() << endl;

    //插入演示
    string a2 = "BBB";
    a2.insert(0, "AAA");
    cout << a2 << endl;
}
int main()
{
    cout<<"******main21************"<<endl;
    main21();
    cout<<"******main22************"<<endl;
    main22();
    cout<<"******main23************"<<endl;
    main23();
    cout<<"******main24************"<<endl;
    main24();
    cout<<"******main25************"<<endl;
    main25();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值