5 STL-string

重新系统学习c++语言,并将学习过程中的知识在这里抄录、总结、沉淀。同时希望对刷到的朋友有所帮助,一起加油哦!

 生命就像一朵花,要拼尽全力绽放!死磕自个儿,身心愉悦!

写在前面,本篇章主要介绍STL中常用容器string。

1.1 string的基本概念

本质:

           string是c++风格的字符串,本质上是一个类。

string和char*的区别:

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

特点:

        (1) string类内部封装了很多成员方法:

                ——查找find、拷贝copy、删除delete、替换replace、插入insert

       (2) string管理了char*所分配的内存,不用担心复制或取值越界等问题,由类内部进行负责。

1.2 string的构造函数

构造函数原型:

  • string();                    创建一个空字符串,例如:string str;
  • string(const char* s);        使用字符串s初始化
  • string(const string& str)    使用一个string对象初始化另一个string对象
  • string(int n,char c)            使用n个字符c初始化string

示例:


#include <iostream>
#include <string>

using namespace std;
// string的构造函数
// string();					创建一个空字符串,例如:string str;
// string(const char* s);		使用字符串s初始化
// string(const string& str)	使用一个string对象初始化另一个string对象
// string(int n,char c)			使用n个字符c初始化string
void test() {
	string s;

	const char* str = "sdfd";
	string s1(str);
	cout << "s1 = " << s1 << endl;

	string s2(s1);
	cout << "s2 = " << s2 << endl;

	string s3(5, 'x');
	cout << "s3 = " << s3 << endl;
}

int main() {
	test();

	system("pause");
	return 0;
}

1.3 string赋值操作

作用:

        给string进行赋值

赋值函数原型:

  • string& operator=(const char* s);                   char*类型字符串        赋值给当前string
  • string& operator=(const string& s);                string类型s                 赋值给当前string
  • string& operator=(char c);                              字符                            赋值给当前string
  • string& assign(const char* s);                        字符串s                       赋值给当前string
  • string& assign(const char* s, int n);               字符串s的前n个字符    赋值给当前string
  • string& assign(const string& s);                     字符串s                        赋值给当前string
  • string& assign(int n, char c);                           用n个字符c                  赋值给当前string

示例:


#include <iostream>
#include <string>

using namespace std;

//string赋值操作
//string& operator=(const char* s);			char*类型字符串		赋值给当前string
//string& operator=(const string& s);		string类型s			赋值给当前string
//string& operator=(char c);				字符				赋值给当前string
//string& assign(const char* s);			字符串s				赋值给当前string
//string& assign(const char* s, int n);		字符串s的前n个字符	赋值给当前string
//string& assign(const string& s);			字符串s				赋值给当前string
//string& assign(int n, char c);			用n个字符c			赋值给当前string

void test() {
	string s1;
	s1 = "hello";
	cout <<"s1 = "<< s1 << endl;

	string s2;
	s2 = s1;
	cout << "s2 = " << s2 << endl;

	string s3;
	s3 = 'a';
	cout << "s3 = " << s3 << endl;

	string s4;
	s4.assign("hi");
	cout << "s4 = " << s4 << endl;

	string s5;
	s5.assign("teststring", 4);
	cout << "s5 = " << s5 << endl;

	string s6;
	s6.assign(s5);
	cout << "s6 = " << s6 << endl;

	string s7;
	s7.assign(5, 'c');
	cout << "s7 = " << s7 << endl;
}

int main() {
	test();

	system("pause");
	return 0;
}

1.4 string字符串拼接

作用:

        在字符串末尾追加字符串

函数原型:

  • string& operator+=(const char* str);                //重载+=操作符
  • string& operator+=(const char c);                    //重载+=操作符
  • string& operator+=(const string& str);              //重载+=操作符
  • string& append(const char* s);                        //把字符串s连接到当前字符串结尾
  • string& append(const char* s, int n);                //把字符串s的前n个字符连接到当前字符串结尾
  • string& append(const string& s);                      //同operator+=(const string& str)
  • string& append(const string& s, int pos, int n);  //将字符串s中从pos开始的n个字符连接到当前字符串结尾

示例:


#include <iostream>
#include <string>

using namespace std;

//string& operator+=(const char* str);				//重载+=操作符
//string& operator+=(const char c);					//重载+=操作符
//string& operator+=(const string& str);			//重载+=操作符
//string& append(const char* s);					//把字符串s连接到当前字符串结尾
//string& append(const char* s, int n);				//把字符串s的前n个字符连接到当前字符串结尾
//string& append(const string& s);					//同operator+=(const string& str)
//string& append(const string& s, int pos, int n);	//字符串s中从pos开始的n个字符连接到字符串结尾

void test() {
	string s1("hello");
	s1 += " echo";
	cout << "s1 = " << s1 << endl;

	string s2;
	s2 += 'x';
	cout << "s2 = " << s2 << endl;

	string s3="say ";
	s3 += s1;
	cout << "s3 = " << s3 << endl;

	string s4 = s3;
	s4.append(" aaa");
	cout << "s4 = " << s4 << endl;

	string s5 = s3;
	s5.append(" 12345",3);
	cout << "s5 = " << s5 << endl;

	string s6 = s3;
	s6.append(s2);
	cout << "s6 = " << s6 << endl;

	string s7 = s3;
	s7.append(" 12345", 1,3);
	cout << "s7 = " << s7 << endl;
}

int main() {
	test();

	system("pause");
	return 0;
}

1.5 string查找和替换

  • 查找:查找指定字符串是否存在
  • 替换:在指定的位置替换字符串

函数原型:

  • int find(const string& str, int pos = 0) const;         //查找str第一次出现位置,从pos开始查找
  • int find(const char* s, int pos = 0) const;              //查找s第一次出现位置,从pos开始查找
  • int find(const char* s, int pos, int n) const;           //从pos位置查找s的前n个字符第一次位置
  • int find(const char c, int pos = 0) const;               //查找字符c第一次出现位置,从pos开始查找
  • int rfind(const string& str, int pos = npos) const;  //查找str最后一次位置,从pos开始查找
  • int rfind(const char* s, int pos = npos) const;       //查找s最后一次出现位置,从pos开始查找
  • int rfind(const char* s, int pos, int n) const;          //从pos查找s的前n个字符最后一次位置
  • int rfind(const char c, int pos = 0) const;              //查找字符c最后一次出现位置
  • string& replace(int pos, int n, const string& str);   //替换从pos开始n个字符为字符串str
  • string& replace(int pos, int n, const char* s);       //替换从pos开始的n个字符为字符串s

注意:

  • find查找,从左往右;rfind查找,从右往左;
  • find和rfind都返回查找到的字符串所在的第一个字符位置,找不到返回-1;
  • replace在替换时,要指定原串被替换的起始位置,被替换字符个数,用什么字符串来替换。

示例:


#include <iostream>
#include <string>

using namespace std;

//int find(const string& str, int pos = 0) const;		//查找str第一次出现位置,从pos开始查找
//int find(const char* s, int pos = 0) const;			//查找s第一次出现位置,从pos开始查找
//int find(const char* s, int pos, int n) const;		//从pos位置查找s的前n个字符第一次位置
//int find(const char c, int pos = 0) const;			//查找字符c第一次出现位置,从pos开始查找
//int rfind(const string& str, int pos = npos) const;	//查找str最后一次位置,从pos开始查找
//int rfind(const char* s, int pos = npos) const;		//查找s最后一次出现位置,从pos开始查找
//int rfind(const char* s, int pos, int n) const;		//从pos查找s的前n个字符最后一次位置
//int rfind(const char c, int pos = 0) const;			//查找字符c最后一次出现位置
//string& replace(int pos, int n, const string& str);   //替换从pos开始n个字符为字符串str
//string& replace(int pos, int n, const char* s);		//替换从pos开始的n个字符为字符串s

// 查找
void test() {
	string s1 = "abcdefgde";
	int pos = s1.find("de");
	if (pos == -1) {
		cout << "not find" << endl;
	}
	else {
		cout << "pos = " << pos << endl;

	}

	// find和rfind的区别:
	// find从左往右找,rfind从右往左找
	pos =s1. rfind("de");
	cout << "pos = " << pos << endl;
}

// 替换
void test2() {
	string s1 = "abcdefg";
	// 从位置1起 3 个字符替换为 1234
	s1.replace(1, 3, "1234");
	cout << "s1 = " << s1 << endl;

	s1 = "abcdefg";
	// 从位置1起 3 个字符替换为 12
	s1.replace(1, 3, "12");
	cout << "s1 = " << s1 << endl;

}

int main() {
	//test();
	test2();

	system("pause");
	return 0;
}

1.6 string字符串比较

作用:

        字符串之间大小比较

比较方式:

        字符串比较是按照字符的ASCII码进行比较的。

        = 返回 0

        > 返回 1

        < 返回 -1

函数原型:

  • int compare(const string& s) const;        字符串与字符串比较
  • int compare(const char* s) const;           字符串与字符串比较

注意:

        字符串比较一般用于比较两个字符串是否相等。

示例:


#include <iostream>
#include <string>

using namespace std;

void test() {
	string s1 = "hello";
	string s2 = "hello";
	int ret = s1.compare(s2);
	if (ret == 0) {
		cout << "s1 等于 s2" << endl;
	}
	else if (ret > 0) {
		cout << "s1 大于 s2" << endl;
	}
	else {
		cout << "s1 小于 s2" << endl;
	}
}

int main() {
	test();

	system("pause");
	return 0;
}

1.7 string字符存取

string中单个字符存取方式有两种:

  • char& operator[](int n);        通过[]数组下标形式取字符
  • char& at(int n);                     通过at方法获取字符

示例:



#include <iostream>
#include <string>

using namespace std;

void test() {
	string s = "abcdefg";
	
	// 获取单个字符
	cout << s[1] << endl;
	cout << s.at(1) << endl;

	// 修改单个字符
	s[1] = 'x';
	cout << s << endl;
	s.at(1) = 'y';
	cout << s << endl;
}

int main() {
	test();

	system("pause");
	return 0;
}

1.8 string插入和删除

作用:

        对string字符串进行插入和删除字符操作

函数原型:

  • string& insert(int pos, const char* s);             //在指定位置n处,插入字符串
  • string& insert(int pos, const string& str);        //在指定位置n处,插入字符串
  • string& insert(int pos, int n, char c);               //在指定位置插入n个字符c
  • string& erase(int pos = 0, int n = npos);               //删除从Pos开始的n个字符

示例:


#include <iostream>
#include <string>

using namespace std;

//string& insert(int pos, const char* s);			//在指定位置n处,插入字符串
//string& insert(int pos, const string& str);		//在指定位置n处,插入字符串
//string& insert(int pos, int n, char c);			//在指定位置插入n个字符c
//string& erase(int pos, int n = npos);			//删除从Pos开始的n个字符
void test() {
	// 插入
	string s = "abc";
	s.insert(1, "123");
	cout << "s = " << s << endl;

	s.insert(2, 3,'x');
	cout << "s = " << s << endl;

	// 删除
	s.erase(2, 3);
	cout << "s = " << s << endl;

}

int main() {
	test();

	system("pause");
	return 0;
}

1.9 string子串

作用:

        从字符串中获取想要的子串

函数原型:

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

示例:


#include <iostream>
#include <string>

using namespace std;

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

void test2() {
	string email = "tom@163.com";
	int pos = email.find("@");
	string userName = email.substr(0, pos);
	cout << userName << endl;
}

int main() {
	test();
	test2();

	system("pause");
	return 0;
}

03-24
### C++ STL Map 的基本用法 `std::map` 是 C++ 标准模板库 (STL) 提供的一种关联容器,它基于红黑树实现[^3]。这种数据结构允许存储键值对,并自动按照键的顺序排列。以下是 `std::map` 的一些核心功能及其使用方法: #### 创建和初始化 可以创建一个空的 `std::map` 或者通过列表初始化器来填充初始值。 ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> myMap; // 创建一个空 map // 使用列表初始化器 std::map<char, int> anotherMap = { {'a', 1}, {'b', 2} }; return 0; } ``` #### 插入元素 可以通过多种方式向 `std::map` 中插入新元素。 ```cpp myMap[1] = "one"; // 方括号操作符会插入或更新已存在的键 myMap.insert({2, "two"}); // insert 方法显式插入一对 key-value myMap.emplace(3, "three"); // emplace 更高效地构建并插入对象 ``` #### 查找元素 查找特定键是否存在以及获取对应的值是一个常见需求。可以利用成员函数 `find()` 来完成此任务[^2]。 ```cpp auto it = myMap.find(2); if(it != myMap.end()) { std::cout << "Key found: " << it->first << ", Value: " << it->second << '\n'; } else { std::cout << "Key not found\n"; } ``` #### 删除元素 删除指定键的条目或者清除整个映射都可以轻松做到。 ```cpp myMap.erase(1); // 移除键为 1 的元素 myMap.clear(); // 清空所有元素 ``` #### 遍历 遍历所有的键值对通常采用迭代器来进行。 ```cpp for(const auto& pair : myMap){ std::cout << pair.first << ": " << pair.second << "\n"; } ``` #### 自定义比较函数 为了更灵活地控制如何排序键,可以提供自定义的比较逻辑给 `std::map` 构造函数[^1]。 ```cpp struct GreaterThanComparator{ bool operator()(const int lhs, const int rhs)const{ return lhs > rhs;} }; std::map<int,std::string,GreaterThanComparator> descendingMap; descendingMap[5]="five"; descendingMap[1]="one"; // 输出将按降序显示因为用了自定义比较器 for(auto &p : descendingMap){ std::cout<< p.first <<": "<< p.second<<"\n"; } ``` ### 性能考量 由于内部采用了平衡二叉搜索树的数据结构,因此大多数涉及单个元素的操作时间复杂度均为 O(log n)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值