美文网首页
string容器

string容器

作者: Sheik | 来源:发表于2021-08-07 23:24 被阅读0次

环境:ide:Mac+clion

视频链接:
https://www.bilibili.com/video/BV1Hb411Y7E5?p=5

string构造函数/赋值/追加

void test(){
    string s1;//默认构造。
    const char * ch = "hello world";
    string s2(ch);//用c语言的字符串来初始化
    cout << "s2="<<s2<<endl;
    string s3(s2);//这里是拷贝构造。
    cout << "s3="<<s3<<endl;
    string s4(5,'a');//前面是几个字符,后面是初始化的字符。
    cout << "s4="<<s4<<endl;//aaaaa

    //可以通过assign进行赋值。
    string s5;
    s5.assign("hello c++");//这里可以通过assign 进行赋值。
    cout << "s5="<<s5<<endl;//hello c++

    s5.assign("sheik",3);//选取第一个参数的三个字符进行赋值
    cout << "s5="<<s5<<endl;//she
    s5.assign(3,'s');//三位都用s 来进行赋值。
    cout << "s5="<<s5<<endl;//sss

    //可以通过append 进行追加
    string s6 = "s";
    s6 += "heik";
    cout << "s6="<<s6<<endl;//sheik

    string s7 = "s";
    s7.append("heik");
    s7.append(".",1);//可以获取前面几个字符。
    s7.append("666777",3,3);//从第三个字符开始,到后面的3个字符
    cout << "s7="<<s7<<endl;//sheik

}

string查找/替换,在字符串中find的值返回为-1 表示没有查到。

find 和rfind 区别:
find从左往右查找;rfind 从右往左查,但是返回的index 也是从左向右数。

void test1(){
    string str = "abcdef";
    int pos = str.find("de");
    cout << "pos:"<<pos<<endl;//3
    int pos1 = str.find("df");
    cout << "pos1:"<<pos1<<endl;//-1

    //替换
    string strR = "abcdef";
    strR.replace(1,3,"6666");//从index =1,到index =3 的位置替换为后面的str
    cout << strR<<endl;//a6666ef
    strR.replace(0,strR.length(),"6666");
    cout << strR<<endl;//6666
}

string字符串比较,可以使用compare函数==0,代表字符串相等。 一般我们只用来做判等操作。

    string str1 = "hello";
    string str2 =  "hello";
    string str3 =  "hhello";
    if (str1.compare(str2) == 0){
        cout << "相等"<<endl;
    }
    cout << str1.compare(str3) <<endl;//-3
    cout << (str1 == str2) <<endl;//1

字符串的存取

void test2(){
    string str = "hello";
    for(int i=0;i<str.size();i++) {
        cout << str[i] << " ";//h e l l o
    }
    cout <<endl;
    for(int i=0;i<str.length();i++) {
        cout << str.at(i) << " ";//可以通过at 来存取。h e l l o
    }
    cout <<endl;

    //修改
    str[0] = 'x';
    cout << str<<endl;//xhello
    str.at(1) = 'z';
    cout << str<<endl;//xzllo
};

字符串的插入和删除

void test3(){
    string str = "hello";
    str.insert(1,"66");
    cout << str<< endl;//h66ello

    str.erase(0,2);
    cout << str<< endl;//6ello
}

字符串字串获取,注意substr 两个参数:第一个参数开始截,后面参数代表截取多少个

    string str = "hello";
    string result = str.substr(0,3);//从第一个参数开始截,后面参数代表截取多少个
    cout << result <<endl;//hel
}

string 中比较常用的就是字符串追加/查找/字符串截取等操作。开发中比较常用的一个类。

相关文章

网友评论

      本文标题:string容器

      本文链接:https://www.haomeiwen.com/subject/iipbvltx.html