C++ 标准模板库(STL)-string

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++ 标准模板库(STL)-string

狂狷   2020-03-16 我要评论

 

总结了一些c++ string库常用的库函数用法

#include <iostream>
#include <string>//string类可以自动管理内存
using namespace std;

int main()
{
    //声明
    string test1="123";
    //cin >> test1;
    //getline(cin, test1); //相同功能
    
    //c初始化
    string test2 = "hello";
    string test3 = "world";
    string test4("great");
    string test41(test2);
    string test42(test2.begin(), test2.end());
    string test43(test2[0], test2[3]);

    //赋值
    test2 = "good";
    test2.assign("hello ");
    test2.assign(test3,1,2);//将test3的从下标为1的字符开始(包括),大小为2的子串赋给test2
    test2.assign(5, 'A');//将5个A赋值给test2


    //获取字符
    cout << test1[0]<<endl;
    cout << test1[1]<<endl;
    cout << test1.at(1)<<endl;


    //交换
    test2.swap(test3);

    //返回子串
    cout << test3.substr() << endl;
    cout << test3.substr(0, 2) << endl;//返回从下标为0的字符开始(包括),大小为2的子串

    //追加字符
    test3 += test2;
    test3.append(test2);
    test3.append(test2, 1, 3);//将test2的从下标为1的字符开始(包括),大小为3的子串追加给test3
    test3.append(5, 'A');//追加5个A
    test3.push_back('A');

    //插入
    test3.insert(3, "abc");
    test3.insert(3, test1);//将test1插入下标3
    test3.insert(3, test1, 2);//将test1的前两个字符插入
    test3.insert(3, test1, 0,2);//将test1的子串(从0开始,长度为2)插入
    test3.insert(3, 5, 'A');//插入5个A

    //清除字符
    string test5("hello");
    test5.clear();//清除所有字符
    cout << test5 << endl;
    test5 = "hello";
    test5.erase();//清除所有字符
    cout << test5 << endl;
    test5 = "hello";
    test5.erase(1, 3);//删除从下标从1开始的3个字符
    cout << test5 << endl;
    test5.erase(1);//删除下标1后所有字符
    cout << test5 << endl;

    //字符串大小
    cout << test2.size() << endl;//字符个数
    cout << test2.length() << endl;//与size()同
    cout << test2.max_size() << endl;//string可包含的最多的字符数,与系统是32位还是64位有关
    cout << test2.capacity() << endl;//在重新分配内存前,string对象的最大容量

    //字符串比较
    cout << test2.compare(test3) << endl;//相同返回0;test2字典顺序先于test3,返回-1;test2字典顺序后于test3,返回1
    cout << test2.compare(0, 3, test3, 0, 3) << endl;//子串比较,表示test2的从0开始,大小为3的子串与 test3的从0开始,大小为3的子串比较
    string test6 = "ABC";
    string test7 = "DEF";
    //字典顺序在前的更小,条件成立返回1,不成立返回0
    cout << (test5 == test6) << endl;
    cout << (test5 < test6) << endl;
    cout << (test5 > test6) << endl;
    cout << (test5 <= test6) << endl;
    cout << (test5 >= test6) << endl;


    //字符串查找
    string test8 = "abcabcaabbj";
    cout<<test8.find("aa", 0)<<endl;//正向查找abc,从下标0开始,返回第一次出现的子串的首字母下标
    cout << test8.rfind("ab") << endl;//逆向查找abc,从下标0开始,返回第一次出现的子串的首字母下标
    cout << test8.find_first_of("ab") << endl;//查找首次出现子串的第一个字符
    cout << test8.find_last_of("ab") << endl;//查找最后一次出现子串的最后一个字符
    cout << test8.find_first_not_of("ab") << endl;//查找与子串不等的第一个字符
    cout << test8.find_last_not_of("ab") << endl;//查找与子串不等的最后一个字符

    return 0;
}

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们