STL基本概念
为了建立数据结构和算法的一套标准,诞生了STL
STL(Standard Template Library标准模板库)
STL从广义分为容器(container)算法(algorithm)迭代器(iterator)
容器和算法之间通过迭代器进行无缝衔接
STL几乎所有的代码都采用了模板类或者模板函数
STL六大组件分别为:
容器:各种数据结构 如verctor,list,deque,set,map等,用来存放数据
算法:各种常用算法,如sort find copy for_each等
迭代器:扮演了容器与算法之间的胶合剂
仿函数:行为类似函数,可作为算法的某种策略
适配器(配接器):一种用来修饰容器或者仿函数或迭代器接口的东西
空间配置器:负责空间的配置与管理
算法
算法分为质变算法和非质变算法
算法(Algorithms)
解释:算法是用来操作容器中数据的函数模板,不依赖于具体的容器类型。
种类分类:
一、非修改序列算法
find:查找元素
count:计数
equal:比较序列
search:搜索子序列
二、修改序列算法
copy:复制
transform:转换
replace:替换
remove:删除
reverse:反转
unique:去重
三、排序和相关操作
sort:排序
stable_sort:稳定排序
partial_sort:部分排序
nth_element:第n元素排序
binary_search:二分查找
merge:合并
四、数值算法
accumulate:累加
inner_product:内积
partial_sum:部分和
STL容器
解释:容器是用来存储和管理数据的类模板,类似于数据结构。
序列式容器:强调值的排序,序列式容器中的每个元素都有固定的位置
关联式容器:二叉树结构 各元素之前没有严格的物理上的顺序关系
一、序列容器(Sequence Containers)
vector:动态数组,支持快速随机访问
deque:双端队列,头尾插入删除高效
list:双向链表,任意位置插入删除高效
forward_list:单向链表(C++11)
array:固定大小数组(C++11)
二、关联容器(Associative Containers)
set:有序唯一元素集合
multiset:有序可重复元素集合
map:键值对集合,键唯一
multimap:键值对集合,键可重复
三、无序关联容器(Unordered Associative Containers)(C++11)
unordered_set:哈希实现的集合
unordered_multiset:哈希实现的可重复集合
unordered_map:哈希实现的映射
unordered_multimap:哈希实现的可重复键映射
四、容器适配器(Container Adapters)
stack:后进先出栈
queue:先进先出队列
priority_queue:优先级队列
迭代器(Iterators)
解释:迭代器是连接容器和算法的桥梁,提供访问容器元素的方法。
种类分类:
一、按功能分类
输入迭代器:只读,只能前移
输出迭代器:只写,只能前移
前向迭代器:读写,只能前移
双向迭代器:读写,可前移后退
随机访问迭代器:读写,支持随机访问
二、按容器分类
vector:随机访问迭代器
deque:随机访问迭代器
list:双向迭代器
set/map:双向迭代器
forward_list:前向迭代器
vector存放内置数据类型project11 filename01
容器:vector
算法:for_each
迭代器:vector
include
using namespace std;
include
include
void myPrint(int val) {
cout << val << endl;
}
//vector容器存放内置数据类型
void test01() {
vector
//向容器中放数据
v.push_back(10);
v.push_back(20);
//通过迭代器访问容器中的数据
vector
vector
// //第一种遍历方式
// while (itBegin != itEnd) {
// cout << *itBegin << endl;
// itBegin++;
// }
//第二种for循环
//第三种遍历方式利用STL提供遍历算法
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test01();
system("pause");
return 0;
}
- vector
::iterator
vector:一个存储整数的向量容器
::iterator:这是 vector 类内部定义的一个类型,表示迭代器类型
整体含义:声明一个指向 vector容器元素的迭代器 - v.begin()
v:一个 vector类型的对象
.begin():vector 类的成员函数,返回指向容器第一个元素的迭代器 - itBegin
迭代器变量名,现在指向 vector 的第一个元素
STL初始-vector存放自定义数据类型
vector<Person*>::iterator itEnd = v.end();
容器嵌套容器
for(vector<vector
string 容器 构造函数project11 filename02
string基本概念
本质:string是C++风格的字符串 而string本质是一个类
string和char区别
char是一个指针
string 是一个类 类内部封装了char,管理这个字符串,是一个char型的容器
特点
string类内部封装了很多成员方法
例如:查找find,拷贝copy,删除replace,插入insert
string管理char所分配的内存 不用担心复制越界和取值越界等,由类内部进行负责
string构造函数
构造函数原型
string(); //创建一个空的字符串 例如string str();
string(const char s)//使用字符串s初始化
string(const string&str)//使用一个string对象初始化另一个string对象
string(int n,char c);//使用n个字符c初始化
include
using namespace std;
include
//string构造函数
void test02() {
string s1; //创建一个空的字符串 例如string str();
const char* str = "sajkfh";//使用字符串s初始化
string s2(str);
cout << s2 << endl;
string s3(s2);//使用一个string对象初始化另一个string对象
cout << s3 << endl;
string s4(10, 'a');//使用n个字符c初始化
cout << s4 << endl;
}
int main() {
test02();
system("pause");
return 0;
}
string容器赋值操作(project11 filename03)
string& operator=(const string& str); // 字符串赋值
string& operator=(const char* s); // C风格字符串赋值
string& operator=(char c); // 字符赋值
string& assign(const string& str); // 字符串赋值
string& assign(const string& str, size_t pos, size_t len = npos); // 子串赋值
string& assign(const char* s); // C风格字符串赋值
string& assign(const char* s, size_t n); // C风格字符串前n个字符
string& assign(size_t n, char c); // n个相同字符
string& assign(InputIterator first, InputIterator last); // 迭代器范围
include
include
using namespace std;
int main() {
// 1. = 操作符赋值
cout << "=== = 操作符赋值 ===" << endl;
string str1;
str1 = "Hello World"; // C风格字符串赋值
cout << "str1: " << str1 << endl;
string str2;
str2 = str1; // string对象赋值
cout << "str2: " << str2 << endl;string str3;
str3 = 'A'; // 字符赋值
cout << "str3: " << str3 << endl;// 2. assign() 函数赋值
cout << "\n=== assign() 函数赋值 ===" << endl;// 2.1 字符串赋值
string str4;
str4.assign("C++ Programming");
cout << "str4: " << str4 << endl;// 2.2 子串赋值
string str5;
str5.assign(str4, 4, 11); // 从位置4开始,取11个字符
cout << "str5: " << str5 << endl;// 2.3 C风格字符串前n个字符
string str6;
str6.assign("Hello World", 5); // 只取前5个字符
cout << "str6: " << str6 << endl;// 2.4 n个相同字符
string str7;
str7.assign(10, '*'); // 10个星号
cout << "str7: " << str7 << endl;// 2.5 迭代器范围赋值
string str8;
str8.assign(str4.begin() + 4, str4.end()); // 从第4个字符到结尾
cout << "str8: " << str8 << endl;// 3. 其他赋值方式
cout << "\n=== 其他赋值方式 ===" << endl;// 3.1 初始化时赋值
string str9 = "Initial Value";
cout << "str9: " << str9 << endl;// 3.2 使用数组赋值
char charArray[] = "Character Array";
string str10;
str10 = charArray;
cout << "str10: " << str10 << endl;// 3.3 链式赋值
string str11, str12, str13;
str11 = str12 = str13 = "Same Value";
cout << "str11: " << str11 << endl;
cout << "str12: " << str12 << endl;
cout << "str13: " << str13 << endl;// 4. 实际应用示例
cout << "\n=== 实际应用示例 ===" << endl;// 动态构建字符串
string message;
message.assign(20, '-');
message += "\n";
message.assign("Welcome to ");
message += "C++ String Demo\n";
message.assign(20, '-');
cout << message << endl;// 提取文件名
string fullPath = "/home/user/documents/file.txt";
string fileName;
size_t lastSlash = fullPath.find_last_of('/');
if (lastSlash != string::npos) {fileName.assign(fullPath, lastSlash + 1, string::npos);
}
cout << "文件名: " << fileName << endl;// 重复模式
string pattern;
pattern.assign(3, 'A');
pattern += "B";
pattern.assign(5, ' '); // 清空并重新赋值
pattern = "New Pattern";
cout << "模式: " << pattern << endl;return 0;
}
string字符串拼接project11 filename04
string& operator+=(const string& str); // 字符串追加
string& operator+=(const char* s); // C字符串追加
string& operator+=(char c); // 字符追加
string& append(const string& str); // 追加字符串
string& append(const string& str, size_t subpos, size_t sublen); // 追加子串
string& append(const char* s); // 追加C风格字符串
string& append(const char* s, size_t n); // 追加C字符串前n个字符
string& append(size_t n, char c); // 追加n个相同字符
string& append(InputIterator first, InputIterator last); // 追加迭代器范围
void push_back(char c); // 在末尾添加一个字符
include
include
using namespace std;
int main() {
// 1. += 操作符拼接(最常用)
cout << "=== += 操作符拼接 ===" << endl;
string str1 = "Hello";
str1 += " World"; // 追加C字符串
cout << "str1: " << str1 << endl;
string str2 = "C++";
str1 += " " + str2; // 追加string对象
cout << "str1: " << str1 << endl;str1 += '!'; // 追加单个字符
cout << "str1: " << str1 << endl;// 2. append() 函数拼接
cout << "\n=== append() 函数拼接 ===" << endl;string str3 = "Hello";
str3.append(" World"); // 追加C字符串
cout << "str3: " << str3 << endl;string str4 = "Programming";
str3.append(" ").append(str4); // 链式调用
cout << "str3: " << str3 << endl;// 2.1 追加子串
string str5 = "Hello";
string str6 = "World Programming";
str5.append(str6, 6, 12); // 从位置6开始,取12个字符
cout << "str5: " << str5 << endl;// 2.2 追加C字符串前n个字符
string str7 = "Hello";
str7.append("World", 3); // 只追加前3个字符
cout << "str7: " << str7 << endl;// 2.3 追加多个相同字符
string str8 = "Hello";
str8.append(3, '!'); // 追加3个感叹号
cout << "str8: " << str8 << endl;// 3. push_back() 函数
cout << "\n=== push_back() 函数 ===" << endl;
string str9 = "Hello";
str9.push_back(' ');
str9.push_back('W');
str9.push_back('o');
str9.push_back('r');
str9.push_back('l');
str9.push_back('d');
cout << "str9: " << str9 << endl;// 4. + 操作符(创建新字符串,不修改原字符串)
cout << "\n=== + 操作符(创建新字符串)===" << endl;
string str10 = "Hello";
string str11 = "World";
string str12 = str10 + " " + str11 + "!";
cout << "str10: " << str10 << endl; // 原字符串不变
cout << "str11: " << str11 << endl; // 原字符串不变
cout << "str12: " << str12 << endl; // 新字符串// 5. 混合使用各种拼接方法
cout << "\n=== 混合使用拼接方法 ===" << endl;
string result;
result = "Start: ";
result += "First Part";
result.append(" ").append("Second Part");
result.push_back(' ');
result += "Third Part";
result.append(2, '!'); // 追加2个感叹号
cout << "result: " << result << endl;// 6. 实际应用示例
cout << "\n=== 实际应用示例 ===" << endl;// 6.1 构建路径
string path;
path.append("/home/");
path += "user";
path.append("/documents/");
path += "file";
path.push_back('.');
path += "txt";
cout << "路径: " << path << endl;// 6.2 构建SQL查询
string tableName = "users";
string condition = "age > 18";
string sqlQuery = "SELECT * FROM ";
sqlQuery += tableName;
sqlQuery.append(" WHERE ").append(condition);
cout << "SQL查询: " << sqlQuery << endl;// 6.3 构建HTML标签
string tagName = "div";
string content = "Hello World";
string className = "container";string html;
html += "<" + tagName + " class=\"" + className + "\">";
html.append(content);
html += "</" + tagName + ">";
cout << "HTML: " << html << endl;// 6.4 构建重复模式
string pattern;
for (int i = 0; i < 5; i++) {pattern += "*** ";
}
cout << "模式: " << pattern << endl;// 7. 性能考虑:大量拼接时使用append可能更高效
cout << "\n=== 大量拼接示例 ===" << endl;
string longString;
// 预分配空间可以提高性能
longString.reserve(1000);for (int i = 0; i < 10; i++) {longString.append("Number: ").append(to_string(i)).append("\n");
}
cout << longString;return 0;
}
字符串查找和提换##project11 filename5
查找函数原型 find从左往右和rfind从右往左
- find() 系列 - 正向查找
cpp
size_t find(const string& str, size_t pos = 0) const; // 查找子串
size_t find(const char* s, size_t pos = 0) const; // 查找C字符串
size_t find(const char* s, size_t pos, size_t n) const; // 查找前n个字符
size_t find(char c, size_t pos = 0) const; // 查找字符 - rfind() 系列 - 反向查找
cpp
size_t rfind(const string& str, size_t pos = npos) const; // 反向查找子串
size_t rfind(const char* s, size_t pos = npos) const; // 反向查找C字符串
size_t rfind(const char* s, size_t pos, size_t n) const; // 反向查找前n个字符
size_t rfind(char c, size_t pos = npos) const; // 反向查找字符 - find_first_of() 系列 - 查找第一个匹配字符
cpp
size_t find_first_of(const string& str, size_t pos = 0) const; // 查找第一个出现的字符
size_t find_first_of(const char* s, size_t pos = 0) const;
size_t find_first_of(const char* s, size_t pos, size_t n) const;
size_t find_first_of(char c, size_t pos = 0) const; - find_last_of() 系列 - 查找最后一个匹配字符
cpp
size_t find_last_of(const string& str, size_t pos = npos) const; // 查找最后一个出现的字符
size_t find_last_of(const char* s, size_t pos = npos) const;
size_t find_last_of(const char* s, size_t pos, size_t n) const;
size_t find_last_of(char c, size_t pos = npos) const; - find_first_not_of() 系列 - 查找第一个不匹配字符
cpp
size_t find_first_not_of(const string& str, size_t pos = 0) const;
size_t find_first_not_of(const char* s, size_t pos = 0) const;
size_t find_first_not_of(const char* s, size_t pos, size_t n) const;
size_t find_first_not_of(char c, size_t pos = 0) const; - find_last_not_of() 系列 - 查找最后一个不匹配字符
cpp
size_t find_last_not_of(const string& str, size_t pos = npos) const;
size_t find_last_not_of(const char* s, size_t pos = npos) const;
size_t find_last_not_of(const char* s, size_t pos, size_t n) const;
size_t find_last_not_of(char c, size_t pos = npos) const;
替换函数原型
replace() 系列
cpp
string& replace(size_t pos, size_t len, const string& str); // 位置和长度
string& replace(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen); // 子串替换
string& replace(size_t pos, size_t len, const char* s); // C字符串替换
string& replace(size_t pos, size_t len, const char* s, size_t n); // C字符串前n个字符
string& replace(size_t pos, size_t len, size_t n, char c); // n个相同字符
string& replace(iterator i1, iterator i2, const string& str); // 迭代器范围
string& replace(iterator i1, iterator i2, const char* s); // 迭代器+C字符串
string& replace(iterator i1, iterator i2, const char* s, size_t n); // 迭代器+前n个字符
string& replace(iterator i1, iterator i2, size_t n, char c); // 迭代器+n个字符
include
include
using namespace std;
int main() {
// ==================== 查找操作示例 ====================
cout << "=== 查找操作示例 ===" << endl;
string text = "Hello World! Welcome to C++ Programming. Hello again!";// 1. find() - 正向查找
cout << "\n1. find() 正向查找:" << endl;
size_t pos1 = text.find("Hello");
cout << "查找 'Hello': " << (pos1 != string::npos ? "找到,位置: " + to_string(pos1) : "未找到") << endl;size_t pos2 = text.find("World", 5); // 从位置5开始查找
cout << "从位置5查找 'World': " << (pos2 != string::npos ? "找到,位置: " + to_string(pos2) : "未找到") << endl;size_t pos3 = text.find('!'); // 查找字符
cout << "查找 '!': " << (pos3 != string::npos ? "找到,位置: " + to_string(pos3) : "未找到") << endl;// 2. rfind() - 反向查找
cout << "\n2. rfind() 反向查找:" << endl;
size_t rpos1 = text.rfind("Hello");
cout << "反向查找 'Hello': " << (rpos1 != string::npos ? "找到,位置: " + to_string(rpos1) : "未找到") << endl;size_t rpos2 = text.rfind('!');
cout << "反向查找 '!': " << (rpos2 != string::npos ? "找到,位置: " + to_string(rpos2) : "未找到") << endl;// 3. find_first_of() - 查找第一个匹配字符
cout << "\n3. find_first_of() 查找第一个匹配字符:" << endl;
string vowels = "aeiouAEIOU";
size_t vowel_pos = text.find_first_of(vowels);
cout << "第一个元音字母位置: " << vowel_pos << ",字符: " << text[vowel_pos] << endl;// 4. find_last_of() - 查找最后一个匹配字符
cout << "\n4. find_last_of() 查找最后一个匹配字符:" << endl;
size_t last_vowel = text.find_last_of(vowels);
cout << "最后一个元音字母位置: " << last_vowel << ",字符: " << text[last_vowel] << endl;// 5. find_first_not_of() - 查找第一个不匹配字符
cout << "\n5. find_first_not_of() 查找第一个不匹配字符:" << endl;
string whitespace = " \t\n";
size_t first_non_ws = text.find_first_not_of(whitespace);
cout << "第一个非空白字符位置: " << first_non_ws << ",字符: " << text[first_non_ws] << endl;// 6. find_last_not_of() - 查找最后一个不匹配字符
cout << "\n6. find_last_not_of() 查找最后一个不匹配字符:" << endl;
string punctuation = "!.,;?";
size_t last_non_punct = text.find_last_not_of(punctuation);
cout << "最后一个非标点字符位置: " << last_non_punct << ",字符: " << text[last_non_punct] << endl;// ==================== 替换操作示例 ====================cout << "\n\n=== 替换操作示例 ===" << endl;string original = "I like apples and apples are delicious";
cout << "原始字符串: " << original << endl;// 1. 简单替换
cout << "\n1. 简单替换:" << endl;
string str1 = original;
str1.replace(7, 6, "oranges"); // 从位置7开始,替换6个字符
cout << "替换后: " << str1 << endl;// 2. 替换所有出现的子串
cout << "\n2. 替换所有出现的子串:" << endl;
string str2 = original;
size_t start_pos = 0;
while ((start_pos = str2.find("apples", start_pos)) != string::npos) {str2.replace(start_pos, 6, "bananas");start_pos += 7; // 移动到替换后字符串的后面
}
cout << "替换所有 'apples': " << str2 << endl;// 3. 使用迭代器替换
cout << "\n3. 使用迭代器替换:" << endl;
string str3 = original;
auto it_begin = str3.begin() + 2;
auto it_end = str3.begin() + 6;
str3.replace(it_begin, it_end, "LOVE");
cout << "迭代器替换: " << str3 << endl;// 4. 替换为多个相同字符
cout << "\n4. 替换为多个相同字符:" << endl;
string str4 = "Password: 123456";
str4.replace(10, 6, 6, '*'); // 替换为6个星号
cout << "密码隐藏: " << str4 << endl;// 5. 使用子串进行替换
cout << "\n5. 使用子串进行替换:" << endl;
string str5 = original;
string replacement = "very tasty fruits";
str5.replace(7, 6, replacement, 5, 5); // 使用replacement的子串(从5开始,取5个字符)
cout << "子串替换: " << str5 << endl;// ==================== 实际应用示例 ====================cout << "\n\n=== 实际应用示例 ===" << endl;// 1. 文件名处理
cout << "\n1. 文件名处理:" << endl;
string filename = "document.backup.txt";
cout << "原始文件名: " << filename << endl;// 更改扩展名
size_t dot_pos = filename.rfind('.');
if (dot_pos != string::npos) {filename.replace(dot_pos + 1, 3, "pdf");cout << "更改扩展名: " << filename << endl;
}// 2. 模板字符串替换
cout << "\n2. 模板字符串替换:" << endl;
string template_str = "Hello {name}, welcome to {company}!";
cout << "模板: " << template_str << endl;// 替换 {name}
size_t name_start = template_str.find("{name}");
if (name_start != string::npos) {template_str.replace(name_start, 6, "Alice");
}// 替换 {company}
size_t company_start = template_str.find("{company}");
if (company_start != string::npos) {template_str.replace(company_start, 9, "Tech Corp");
}
cout << "替换后: " << template_str << endl;// 3. 数据清理
cout << "\n3. 数据清理:" << endl;
string dirty_data = "My email is example@domain.com and phone is 123-456-7890";
cout << "原始数据: " << dirty_data << endl;// 隐藏邮箱
size_t at_pos = dirty_data.find('@');
if (at_pos != string::npos) {size_t dot_pos = dirty_data.find('.', at_pos);if (dot_pos != string::npos) {dirty_data.replace(at_pos - 3, 3, "***"); // 隐藏用户名部分}
}// 隐藏电话号码
size_t phone_start = dirty_data.find("123-456-7890");
if (phone_start != string::npos) {dirty_data.replace(phone_start, 12, "***-***-****");
}
cout << "清理后: " << dirty_data << endl;// 4. 格式化数字
cout << "\n4. 格式化数字:" << endl;
string number_str = "1234567890";
cout << "原始数字: " << number_str << endl;// 添加千位分隔符
for (int i = number_str.length() - 3; i > 0; i -= 3) {number_str.replace(i, 0, ",");
}
cout << "格式化后: " << number_str << endl;return 0;
}
字符串比较project11 filename06
int compare(const string& str) const noexcept; // 比较两个字符串
int compare(size_t pos, size_t len, const string& str) const; // 比较子串
int compare(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const; // 比较子串
int compare(const char* s) const; // 与C字符串比较
int compare(size_t pos, size_t len, const char* s) const; // 与C字符串子串比较
int compare(size_t pos, size_t len, const char* s, size_t n) const; // 与C字符串前n字符比较
include
using namespace std;
int main() {
string str1 = "apple";
string str2 = "banana";
string str3 = "apple";
string str4 = "Apple";
// 1. 基本比较
cout << "\n1. 基本比较:" << endl;
cout << "apple.compare(banana): " << str1.compare(str2) << endl; // 负数,apple < banana
cout << "banana.compare(apple): " << str2.compare(str1) << endl; // 正数,banana > apple
cout << "apple.compare(apple): " << str1.compare(str3) << endl; // 0,相等
cout << "apple.compare(Apple): " << str1.compare(str4) << endl; // 正数,区分大小写
}
string字符存取project11 filename7
string中单个字符存取方式有两种
char& operator[](int n);//通过[]方式取字符
char at(int n);//通过at方法获取字符
include
include
using namespace std;
int main() {
string str = "Hello C++ World";
cout << "原始字符串: " << str << endl;
cout << "字符串长度: " << str.length() << endl << endl;// ==================== 基本遍历示例 ====================cout << "=== 使用[]运算符遍历 ===" << endl;
cout << "字符遍历: ";
for (size_t i = 0; i < str.length(); i++) {cout << str[i] << " ";
}
cout << endl;cout << "索引和字符: " << endl;
for (size_t i = 0; i < str.length(); i++) {cout << "索引 " << i << ": '" << str[i] << "'" << endl;
}
cout << endl;cout << "=== 使用at()方法遍历 ===" << endl;
cout << "字符遍历: ";
for (size_t i = 0; i < str.length(); i++) {cout << str.at(i) << " ";
}
cout << endl;cout << "索引和字符: " << endl;
for (size_t i = 0; i < str.length(); i++) {cout << "索引 " << i << ": '" << str.at(i) << "'" << endl;
}
cout << endl;// ==================== 遍历时修改字符 ====================cout << "=== 遍历时修改字符 ===" << endl;
string text1 = "hello world";
string text2 = "hello world";cout << "修改前: " << text1 << endl;// 使用[]运算符修改
for (size_t i = 0; i < text1.length(); i++) {if (text1[i] == ' ') {text1[i] = '_'; // 将空格替换为下划线}
}
cout << "使用[]修改后: " << text1 << endl;// 使用at()方法修改
for (size_t i = 0; i < text2.length(); i++) {if (text2.at(i) == ' ') {text2.at(i) = '-'; // 将空格替换为连字符}
}
cout << "使用at()修改后: " << text2 << endl << endl;// ==================== 实际应用遍历示例 ====================cout << "=== 实际应用遍历示例 ===" << endl;// 1. 统计字符类型
cout << "1. 统计字符类型:" << endl;
string sample = "Hello World 123!";
int letters = 0, digits = 0, spaces = 0, others = 0;for (size_t i = 0; i < sample.length(); i++) {char ch = sample[i]; // 使用[]访问if (isalpha(ch)) {letters++;} else if (isdigit(ch)) {digits++;} else if (isspace(ch)) {spaces++;} else {others++;}
}cout << "字符串: " << sample << endl;
cout << "字母: " << letters << ", 数字: " << digits;
cout << ", 空格: " << spaces << ", 其他: " << others << endl << endl;// 2. 查找特定字符位置
cout << "2. 查找特定字符位置:" << endl;
string data = "programming";
char target = 'm';cout << "在 '" << data << "' 中查找 '" << target << "' 的位置:" << endl;
for (size_t i = 0; i < data.length(); i++) {if (data.at(i) == target) { // 使用at()访问cout << "找到 '" << target << "' 在位置 " << i << endl;}
}
cout << endl;// 3. 字符串反转(遍历实现)
cout << "3. 字符串反转:" << endl;
string original = "ABCDE";
string reversed = original;cout << "原字符串: " << original << endl;size_t len = reversed.length();
for (size_t i = 0; i < len / 2; i++) {// 使用[]交换字符char temp = reversed[i];reversed[i] = reversed[len - 1 - i];reversed[len - 1 - i] = temp;
}cout << "反转后: " << reversed << endl << endl;// 4. 大小写转换遍历
cout << "4. 大小写转换:" << endl;
string mixed = "Hello World";cout << "原始: " << mixed << endl;// 转换为大写
for (size_t i = 0; i < mixed.length(); i++) {mixed[i] = toupper(mixed[i]);
}
cout << "大写: " << mixed << endl;// 转换为小写
for (size_t i = 0; i < mixed.length(); i++) {mixed.at(i) = tolower(mixed.at(i));
}
cout << "小写: " << mixed << endl << endl;// 5. 提取数字字符
cout << "5. 提取数字字符:" << endl;
string alphanumeric = "abc123def456ghi";
string numbersOnly;for (size_t i = 0; i < alphanumeric.length(); i++) {if (isdigit(alphanumeric[i])) {numbersOnly += alphanumeric[i];}
}cout << "原始字符串: " << alphanumeric << endl;
cout << "仅数字: " << numbersOnly << endl << endl;// 6. 字符计数
cout << "6. 字符计数:" << endl;
string word = "mississippi";
char countChar = 's';
int count = 0;for (size_t i = 0; i < word.length(); i++) {if (word.at(i) == countChar) {count++;}
}cout << "在 '" << word << "' 中,字符 '" << countChar;
cout << "' 出现了 " << count << " 次" << endl << endl;// 7. 逐字符处理显示
cout << "7. 逐字符处理显示:" << endl;
string message = "Hello";cout << "逐字符构建: ";
for (size_t i = 0; i < message.length(); i++) {cout << message[i];if (i < message.length() - 1) {cout << " -> ";}
}
cout << endl;return 0;
}
string容器插入和删除project filename08
string & insert(int pos,const char* s);//插入字符串
string & insert(int pos,const string& s);//插入字符串
string & insert(int pos,int n,char c);//在指定位置插入n个字符c
string & insert(int pos,int n = npos); //删除从Pos开始的n个字符
include
include
using namespace std;
int main() {
string text = "Programming";
cout << "初始字符串: " << text << endl;// 插入示例
text.insert(0, "C++ "); // 开头插入
cout << "开头插入: " << text << endl;text.insert(7, "is fun "); // 中间插入
cout << "中间插入: " << text << endl;text.insert(text.length(), "!!!"); // 末尾插入
cout << "末尾插入: " << text << endl;text.insert(3, 2, '+'); // 插入2个'+'字符
cout << "插入字符: " << text << endl;// 删除示例
text.erase(3, 2); // 删除2个'+'
cout << "删除字符: " << text << endl;text.erase(7, 6); // 删除"is fun"
cout << "删除子串: " << text << endl;text.erase(3); // 从位置3删除到末尾
cout << "删除到末尾: " << text << endl;return 0;
}
string容器 子串获取
从字符串中获取想要的字符串
函数原型:string substr(int pos = 0,int n = nops)const;
include
include
using namespace std;
int main() {
string text = "Hello World";
// 简单示例
cout << "原始: " << text << endl;
cout << "前5字符: " << text.substr(0, 5) << endl; // Hello
cout << "后5字符: " << text.substr(6) << endl; // World
cout << "中间: " << text.substr(2, 3) << endl; // lloreturn 0;
}