Add stl string
ci/woodpecker/push/test Pipeline was successful Details

This commit is contained in:
Sainnhe Park 2023-02-28 20:38:11 +08:00
parent 56a0500b7b
commit 1f13bd1698
2 changed files with 58 additions and 0 deletions

View File

@ -65,6 +65,7 @@
- [总结](./stl.md)
- [排序](./stl_sorting.md)
- [哈希表](./stl_hash_table.md)
- [字符串](./stl_string.md)
# 技巧

57
notes/src/stl_string.md Normal file
View File

@ -0,0 +1,57 @@
# 字符串
```cpp
#include <iostream>
#include <string>
int main(int argc, const char *argv[]) {
// 输出到 stdout
std::cout << "Input your string: ";
// 从 stdin 读取
std::string input;
// 不能读入空格,以空格、制表符、回车符作为结束标志
std::cin >> input;
// 可以读入空格和制表符,以回车符作为结束标志
std::getline(std::cin, input);
// 创建一个字符串
std::string str1 = "surface";
// 深拷贝一个字符串
std::string str2 = str1;
std::string str3 = std::string(str1);
// 从下标 1 开始深拷贝
std::string str4 = std::string(str1, 1);
// 从下标 1 开始深拷贝,长度为 2
std::string str5 = std::string(str1, 1, 2);
std::string str6 = str1.substr(1, 2);
// 长度
int len = str1.length();
// 是否为空
bool isEmpty = str1.empty();
// 类型转换
int val = std::stoi("1024");
// 读取
std::cout << str1[0] << std::endl;
std::cout << str1.front() << std::endl;
std::cout << str1.back() << std::endl;
// 在结尾追加
str1.append(" book");
// 在索引为 6 的字符前面插入字符串
str1.insert(6, "foo");
// 替换从 0 开始,长度为 2 的子字符串
str1.replace(0, 2, "msft");
// 删除从 0 开始,长度为 4 的子字符串
str1.erase(0, 4);
// 两个字符串组合
std::string str7 = str1 + str2;
// 两个字符串比较
bool isEqual = str1 == str2;
// 寻找子字符串出现的起始位置
int startIndex = str1.find("foo");
// 从索引 2 开始往后搜索
startIndex = str1.find("foo", 2);
}
```