c++学习第十三讲---STL常用容器---string容器

string容器:

一、string的本质:

string和char*的区别:

char*是一个指针
string是一个类,封装了char*,管理这个字符串,是char*的容器。

二、string构造函数:

string() ;                            //空字符串
string(const char* s) ;       //用字符串s初始化
string(const string& str) ;  //拷贝构造
string(int n, char c) ;         //用n个字符c初始化

	string str1;
	char s[12] = "hello world";
	string str2(s);
	string str3(str2);
	string(10, 'a');

三、string赋值操作:

(1)通过 = 重载赋值:

string& operator=(const char* s);     //用字符串s赋值

string& operator=(const string& s);  //用字符串s赋值

string& operator=(char c);                //用字符c赋值

	char s[12] = "hello world";
	string str1 = s;
	string str2 = str1;
	string str3;
	str3 = 'a';

(2)通过 assign 函数赋值:

string& assign(const char* s);          //用字符串s赋值

string& assign(const char* s, int n); //用字符串s前n个字符赋值

string& assign(const string& s);       //用字符串s赋值

string& assign(int n, char c);            //用n个字符c赋值

	string str1;
	str1.assign("hello world");
	str1.assign("hello world",5);
	string str2;
	str2.assign(str1);
	str2.assign(10, 'a');

四、string的拼接:

(1)通过 += 重载拼接:

string& operator+= (const char* str) ;

string& operator+= (const char c) ;

string& operator+= (const string& str) ;

	string str1 = "hello ";
	str1 += "world";
	str1 += '!';
	string str2 = "haha ";
	str1 += str2;

(2)通过 append 函数拼接:

string& append(const char* s) ;

string& append(const char* s, int n) ;               //把字符串s的前n个字符连接到当前字符串结尾

string& append(const string& s) ;

string& append(const string& s, int pos, int n) ;//字符串s从pos开始的n个字符连接到字符串结尾
(注:字符串下标从0开始)

	string str1 = "hello";
	str1.append(" ");
	str1.append("world", 1);
	string str2 = "or";
	str1.append(str2);
	str1.append("world", 3, 2);
	cout << str1 << endl;

五、string的查找和替换:

(1)查找:find 和 rfind 函数

注:(1)查找函数返回值:找到返回位置,没找到返回 -1。

       (2)rfind从右往左查找,find从左往右查找

(2)替换:replace 函数

c++学习第十三讲---STL常用容器---string容器_第1张图片

	string str1 = "abcdefg";
	int pos = str1.find("de");//3
	str1.replace(1, 2, "aa");

六、string的比较:compare 函数

比较方式:逐个按ASCII码值进行对比。

=:返回 0

>:返回 1

<:返回 -1

int compare(const string& s) const;

	cout << str[0] << endl;

int compare(const char* s) const;

	string str1 = "abc";
	string str2 = "abd";
	cout << str1.compare(str2) << endl;
	cout << str1.compare("abd") << endl;

七、string的取用:

(1)通过 [ ] 重载取用

	cout << str[0] << endl;

(2)通过 at 函数取用

char& at (int n);

	cout << str.at(0) << endl;

八、字符串插入和删除:

string& insert (int pos, const char* s);        //在指定位置插入字符串s

string& insert (int pos, const string& str);   //在指定位置插入字符串s

string& insert (int pos, int n, char c);          //在指定位置插入n个字符c

string& erase (int pos, int n = npos);          //删除从pos开始的n个字符

	string str1 = "world";
	str1.insert(1, "111");
	str1.erase(1, 3);

九、string子串:

功能:从字符串中获取想要的子串。

string substr (int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串

	string str = "abcdef";
	cout << str.substr(1, 3) << endl;

你可能感兴趣的:(c++,学习,开发语言)