(18)C++ string和标准模板库

 

 一、stringl类

1.string构造函数

    string a1("abc");//初始化字符串
    cout<<a1<<endl;//abc

    string a2(6, '#');//n个字符
    cout << a2 << endl;//######

    string a3(a1);//复制
    cout << a3 << endl;//abc

    char c[] = "hello";
    string a4(c,3);//从起始截取前n个字符
    cout << a4 << endl;//hel

    string a5(c+1,c+3);//截取一段字符串
    cout << a5 << endl;//el

    string a6(c, 1,3);//从n1开始截取n2个
    cout << a6 << endl;//ell

 2.字符串输入

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

int main() {

    //string str1;
    //cin >> str1;//输入字符串方法1
    //cout << str1 << endl;

    string str2;
    getline(cin, str2);//输入字符串方法2
    cout << str2 << endl;
}

3.使用字符串

(1)比较字符串 比较ASCII码

    int a = 0;
    if ('abc' > 'daaa') {
         a = 1;
    }
    else {
        a = -1;
    }
    cout << a << endl;

(2)字符串长度

    string a = "abc";
    cout << a.length() << endl;
    cout << a.size() << endl;

(3)查找

查找是否包含此字符串,有则返回首字符索引,没有返回 npos

    string a = "aabc";
    cout << a.find("bc111")<<endl;

npos表示字符串可存储的最大字符数

 

 

二、智能指针模板类

 智能指针定义后,离开代码块指针将过期

    auto_ptr<string> str(new string);//C++98方式,过时
    unique_ptr<string> str(new string);//C++11 一般使用这个
    shared_ptr<string> str(new string);//C++11 如果多个指针指向同一个对象,用这个

 

三、标准模板库

 

posted @ 2019-09-29 16:08  富坚老贼  阅读(361)  评论(0编辑  收藏  举报