【STL】string容器的初始化、拼接、赋值、查找、替换、比较、子串、插入和删除

mac2024-03-17  32

一、string特性

string是STL的字符串类型,通常用来表示字符串。而在使用string之前,字符串通常是用char表示的,string与char都可以用来表示字符串。 说到string的特性,就不得不和char类型的字符串对比: 1、char是一个指针,string是一个类 string封装了char*,管理这个字符串,是一个char型的容器。 2、string封装了很多实用的成员方法 查找find,拷贝copy,删除delete,替换replace,插入insert 3、不用考虑内存释放和越界 string管理char所分配的内存,每一次string的复制,取值都由string类负责维护,不用担心复制越界和取值越界等。 4、string和char可以相互转换,string转char通过string提供的c_str()方法。

//string转char* string str=“abcdefg”; const char* cstr=str.c_str(); //char*转string char* s=“abcdefg”; string sstr(s);

二、string容器的初始化、拼接、赋值、查找、替换、比较、子串、插入和删除

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

///1-初始化

void test01() { string s1;//调用无参构造 string s2(10, 'a'); string s3("abcdefg"); string s4(s3);//拷贝构造 cout << s1 << endl; cout << s2 << endl; cout << s3 << endl; cout << s4 << endl; }

//2-赋值操作

void test02() { string s1; string s2("appp"); s1 = "abcdefg"; cout << s1 << endl; s1 = s2; cout << s1 << endl; s1 = 'a'; cout << s1 << endl; //成员方法 assign 进行赋值 s1.assign("jkl"); cout << s1 << endl; }

//3-取值操作

void test03() { string s1 = "abcdefg"; //重载[]操作符 for (int i = 0; i < s1.size(); ++i) { cout << s1[i] << " "; } cout << endl; //at成员函数 for (int i = 0; i < s1.size(); ++i) { cout << s1.at(i) << " "; } cout << endl; //区别:[]方式 如果访问越界,直接挂掉 // at方式 访问越界,抛出异常out_of_range; try { cout << s1.at(100) << endl; } catch(...){ cout << "越界" << endl; } }

/4-拼接操作

void test04() { string s = "abcd"; string s2 = "1111"; s += "abcd"; s += s2; cout << s << endl;//abcdabcd1111 string s3 = "2222"; s2.append(s3);//把s3加到s2后面 cout << s2 << endl;// 11112222 string s4 = s2 + s3;//把s3加到s2的后面 cout << s4 << endl;//111122222222 }

5-查找和替换

void test05() { string s = "abcdefgsadasaafgddefgde"; //查找第一次出现的位置 int pos=s.find("fg"); cout << "pos:"<<pos << endl; //查找最后一次出现的位置 pos = s.rfind("fg"); cout << "pos:" << pos << endl; }

/替换操作

void test06() { string s = "abcdefg"; s.replace(0, 2, "111"); cout << s << endl; }

6-字符串比较

void test07() { string s1 = "abcd"; string s2 = "abce"; if (s1.compare(s2) == 0) { cout << "字符串相等" << endl; } cout << "不相等" << endl; }

//7-string 子串操作

void test08() { string s = "abcdefg"; string sub=s.substr(1, 3); cout << sub << endl; }

/8-string插入和删除

void test09() { string s = "abcdefg"; s.insert(3, "111");//abc111defg cout << s << endl; s.erase(0, 2);//c111defg cout << s << endl; }

i

nt main(void) { //test01(); //test03(); //test04(); //test05(); //test06(); //test07(); //test08(); test09(); return 0; }
最新回复(0)