标准模板库(STL)使用说明 之 2 string

版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89597380

STL(standard template library)是一个具有工业强度的高效C++程序库。它被容纳于C++标准程序库(C++ Standard Library)中,是ANSI/ISO C++标准中最新的也是极具革命性的一部分。该库包含了诸多在计算机科学领域里所常用的基本数据结构和基本算法。为广大C++程序员们提供了一个可扩展的应用框架,高度体现了软件的可复用性。
常见的容器主要有 vector,string,deque,pari,set,multiset,map,multimap 8种。
本文介绍:

  • 字符串string
    • string类型转换为char*字符串
    • char*类型字符串转换为string类型字符串
    • string初始化
    • string容器字符串赋值和存取
    • string容器拼接操作
    • string查找和替换 比较
    • string 比较 子串 插入和删除
//string类型转换为char*字符串
string s = "abc";
const char* str = s.c_str();

//char*类型字符串转换为string类型字符串
char* str2 = "acbd";
string s2(str2);

string s; //默认构造
string s2 = "acbd";
string s3(s2);
string s4(10, 'c');
//string容器赋值
string s;
s = "abcd";

string s2;
s2.assign("pppp");


//string容器存取
string s3 = "abcdefg";
//[]访问方式访问越界时候,不会抛异常,直接挂掉
//at会抛出异常
try{
//cout << s3[100] << endl;
cout << s3.at(100) << endl;
}
catch (...){
cout << "访问越界!" << endl;
}

string s1 = "aaa";
string s2 = "bbb";
string s3 = s1 + s2;
s1 += s2;
//成员方法方式 append
s1.append(s2);

string s = " acbdefg";
//查找
string target = "bd";
int pos = s.find(target);
char* target2 = "ef";
int pos2 = s.find(target2);
//从后往前查找
int pos3 = s.rfind(target);

//字符串替换
string s1 = "acbd";
s.replace(0, 2, s1);

//比较
string s1 = "abc";
string s2 = "abd";
int ret = s1.compare(s2);

//子串
string s3 = "abcdefg";
string s4 = s3.substr(0,2);
//插入和删除
string s5 = "abcd";
s5.insert(0, "pppp");
string s6 = "qqqq";
s5.insert(s5.size(), s6);
s5.erase(0,4);
  •  

猜你喜欢

转载自blog.csdn.net/mafucun1988/article/details/89597380
今日推荐