C++的String容器

一.基本概念

二.构造函数

#include <iostream>
#include<string>
using namespace std;
/*string容器的构造方法

    string();               //构造一个空的字符串
    string(const char* s)   //使用字符串s初始化
    string(const string &s) //使用另一个字符串初始化
    string(int n ,char c)   //利用n个字符c初始化
    */

void test01() {             //string初始化的测试函数
    string s1;              //默认构造函数,空字符串

    const char* s = " I live u";
    string s2(s);

    string s3(s2);

    string s4(10, 'a');
    
    
}
int main()
{
   
}

三.赋值操作

void test02() {                  //赋值操作测试函数
    string s21;                 //通过等号赋值
    s21 = "dididi";

    string s22 = s21;  

    string s23;                 //通过asign()函数赋值
    s23.assign("dududud");

    string s24;
    s24.assign("kkkkkkk", 3);

    string s25;
    s25.assign(s24);

    cout <<"s21"+ s21 << endl;
    cout <<"s22"+ s22 << endl;
    cout << "s23" + s23 << endl;
    cout << "s24" + s24 << endl;
    cout << "s25" + s25 << endl;
    

}

四.字符串拼接

void test03() {                 //字符串拼接测试函数
    string s31 = "you ";         //通过 + 完成字符串的拼接
    s31 = s31 + "they";

    string s32 = "I ";
    s32 += s31;

    string s33 = "who ";        //通过append()函数完成字符串的拼接
    s33.append("are you");

    string s34 = "cool ";
    s34.append(s33);

    string s35 = "shift";
    s35.append(s34, 2);

    string s36 = "time";
    s36.append(s35, 1, 2);      //将s35从第一个位置的字符开始的2个字符拼接到字符串s36后面


    cout << "s31 = " + s31 << endl;
    cout << "s32 = " + s32 << endl;
    cout << "s33 = " + s33 << endl;
    cout << "s34 = " + s34 << endl;
    cout << "s35 = " + s35 << endl;
    cout << "s36 = " + s36 << endl;

    }

五.查找和替换

void test04() {                 //字符串查找测试函数
    string s41 = "aaaaabbcaaaabbca";        //find():从左往右开始查找,rfind从右往左查找
    string s42 = "bbc";
    cout << s41.find("bbc") << endl;
    cout << s41.find(s42) << endl;
    cout << s41.rfind("bbc") << endl;
    cout << s41.rfind(s42) << endl;

}

void test05() {                 //字符串替换测试函数
    string s51 = "aaaaaaaaaaaaa";
    string s52 = "hhh";
    string s53 = s51.replace(1, 3, s52);
    string s54 = s51.replace(4, 2, "kk");
    cout << "s53 = " + s53 << endl;
    cout << "s54 = " + s54 << endl;


}

六.字符串比较

void test06() {
    string s61 = "abcd";
    string s62 = "abcde";

    cout << s61.compare(s62) << endl;
    cout << s61.compare("abcd") << endl;
    cout << s61.compare("abc") << endl;
}

七.字符存取

void test07() {
    string s71 = "abcdefg";
    cout <<"输出字符串第3个字符"<< s71[2] << endl;
    cout << "输出字符串第4个字符" << s71.at(3) << endl;
}

八.插入和删除

void test08() {
    string s81 = "aaabbbccc";
    string str82 = "ooo";
    cout << s81.insert(8, str82) << endl;   

    string s83 = "hello";
    cout << s83.erase(1, 2)<< endl;//删除第一个位置开始的两个字符
}

 

九.子串

void test09() {
    string s91 = "abcccccccc";
    cout << s91.substr(4, 2) << endl;
}
发布了54 篇原创文章 · 获赞 14 · 访问量 3609

猜你喜欢

转载自blog.csdn.net/q2511130633/article/details/104450712
今日推荐