字符串-string容器(c++)

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

void test1(){
    string s1;//默认构造 创建一个空字符串
    cout<<s1<<endl;

    const char *s2="hello c++";//字符串初始化(c语言)
    cout<<s2<<endl;

    string s3(s2);//对象初始化对象
    cout<<s3<<endl;

    string s4(4,'a');//使用4个字符a初始化
    cout<<s4<<endl;
}
void test2(){
    string s1="hello world";//字符串赋值 hello world
    string s2=s1;//对象赋值对象 hello world
    string s3="c";//单个字符赋值 c

    string s4,s5,s6,s7;
    s4.assign("hello world");//hello world
    s5.assign("hello world",5);//hello
    s6.assign(s5);//hello
    s7.assign(6,'a');//aaaaaa
}
void test3(){
    string s1="";
    s1+="喜欢";//添加字符串  我喜欢
    s1+=":";//添加单个字符  我喜欢:

    string s2="星空";
    s1+=s2;//字符串相加 我喜欢:星空

    string s3="";
    s3.append("");//你爱
    s3.append("土地123",2);//你爱土地
    s3.append(s2);//你爱土地星空
    s3.append(s2,0,1);//参数二 从哪个位置开始截取 参数三 截取字符个数 你爱土地星空星
}
void test4(){
    string st1="abcdef";
    int pos=st1.find("bc");//可以查找字符串 也可以查找单个字符
    cout<<pos<<endl;//1

    string st2="abcdefghabj";
    int pos1=st2.find("ab");//find 从左往右查找
    cout<<pos1<<endl;//0
    int pos13=st2.find("ab",1);//find 从左往右查找 从第一个位置开始找(跳过某一位置)rfind也可以
    cout<<pos1<<endl;//8
    int pos2=st2.rfind("ab");//rfind 从右往左查找 
    cout<<pos2<<endl;//8

    st1.replace(1,3,"2222");//可以替换字符串 也可以替换单个字符 不能用字符直接替换字符 需要借助迭代器
    cout<<st1<<endl;//a2222ef
}
void test5(){
    string s1="hello";
    string s2="xello";
    if(s1.compare(s2)==0){
        cout<<"s1=s2"<<endl;
    }
    else if(s1.compare(s2)==1){
        cout<<"s1>s2"<<endl;
    }
    else if(s1.compare(s2)==-1){
        cout<<"s1<s2"<<endl;
    }
}
void test6(){//我最喜欢的string功能
    string s1="hello";//通过下标读取
    cout<<s1[2]<<endl;//l
    cout<<s1.at(2)<<endl;//l

    s1[0]='x';//两种方式都只能修改单个字符
    s1.at(1)='x';
    cout<<s1<<endl;//xxllo
}
void test7(){
    string s1="hello";
    s1.insert(1,"999");//在第一个位置插入999
    cout<<s1<<endl;//h999ello

    s1.erase(3,2);//在第三个位置 删除两个字符
    cout<<s1<<endl;//h99llo
}
void test7(){
    string s1="hello";
    string stu=s1.substr(1,3);//从1号位置 截取3个位置
    cout<<stu<<endl;//ell
}
int main(){
    //test1() 构造函数
    //test2() 赋值操作
    //test3() 字符串拼接
    //test4() 查找和替换
    //test5() 字符串比较
    //test6() 字符串存取
    //test7() 插入和删除
    //test8() string 子串
    return 0;
}

 

posted @ 2021-01-27 19:16  大耿2844  阅读(91)  评论(0)    收藏  举报