STL之string

为什么要写STL浅谈这个系列,因为最近我在准备蓝桥杯,刷题的时候经常要用到STL,准备补一补,但一直没有找到一个好的视频和资料,最开始准备跟着c语言中文网学,但觉得太繁杂了,最后在b站(b站上计算机类的教学视频挺多的)上找了一个视频学的。这个系列相当于我的一个整理。

这个系列只是浅谈,但刷题应该够了。

今天讲<string>,直接上代码(本人文采有限,习惯代码+注释)。

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

int main()
{
    //输入输出
    string str1;
    //cin>>str1; //无法输入有空格的字符串 
    //cout<<str1<<endl;

    getline(cin, str1); //输入一行字符串 
    cout << str1 << endl;

    //字符串拼接 
    string str2 = "hello";
    str2 += " world!";
    cout << str2 << endl; //str2="hello wrold!"

    //字符串删除指定元素 
    str2.erase(str2.begin() + 1); //删除元素'e'
    /*string.begin()头迭代器,指向第一个元素
      string.end()尾迭代器,指向最后一个元素的后一个位置*/
    cout << str2 << endl; //str2="hllo wrold!"

    //字符串截取 
    str2 = "hello wrold";
    string str3 = str2.substr(1, 3); //第一个参数是起始下标,第二个参数是截取长度 
    cout << str3 << endl; //str3="ell"

    //for循环
    for (int i = 0; i < str2.length(); i++) //字符串长度:str.length()
        cout << str2[i];
    cout << endl;
    //迭代器循环
    for (string::iterator it = str2.begin(); it < str2.end(); it++)
        cout << *it;
    cout << endl;
    //auto指针 
    for (auto it = str2.begin(); it < str2.end(); it++)
        cout << *it;
    cout << endl;
    //foreach循环
    for (auto ch : str2)
        cout << ch;
    cout << endl;

    //字符串插入
    str2.insert(1, "ello"); //第一个参数是起始下标,第二个参数是插入字符串
    cout << str2 << endl; //str2="helloello wrold"

    //字符串交换
    str3 = "end!";
    str2.swap(str3);
    cout << str2 << endl; //str2 = "end!"
    return 0;
}
posted @ 2020-04-05 21:59  你的名字_子集  阅读(259)  评论(0编辑  收藏  举报