STL初识project11

news/2025/11/5 18:30:05/文章来源:https://www.cnblogs.com/maylet/p/19190527

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::iterator

include

using namespace std;

include

include

void myPrint(int val) {
cout << val << endl;
}
//vector容器存放内置数据类型
void test01() {
vectorv;//v是变量名
//向容器中放数据
v.push_back(10);
v.push_back(20);
//通过迭代器访问容器中的数据
vector::iterator itBegin = v.begin();//起始迭代器 指向容器第一个元素的位置
vector::iterator itEnd = v.end();//结束迭代器 指向容器中最后一个元素的下一个位置
// //第一种遍历方式
// while (itBegin != itEnd) {
// cout << *itBegin << endl;
// itBegin++;
// }
//第二种for循环
//第三种遍历方式利用STL提供遍历算法
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test01();
system("pause");
return 0;
}

  1. vector::iterator
    vector:一个存储整数的向量容器
    ::iterator:这是 vector 类内部定义的一个类型,表示迭代器类型
    整体含义:声明一个指向 vector 容器元素的迭代器
  2. v.begin()
    v:一个 vector 类型的对象
    .begin():vector 类的成员函数,返回指向容器第一个元素的迭代器
  3. itBegin
    迭代器变量名,现在指向 vector 的第一个元素

STL初始-vector存放自定义数据类型

vector<Person*>::iterator itEnd = v.end();

容器嵌套容器

for(vector<vector>::iterator vit = (it).begin;vit != (it).end;vit++)

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从右往左

  1. 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; // 查找字符
  2. 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; // 反向查找字符
  3. 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;
  4. 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;
  5. 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;
  6. 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;

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/957055.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

告别漫长GC停顿:深入解析G1如何实现可预测的毫秒级响应

告别漫长GC停顿:深入解析G1如何实现可预测的毫秒级响应G1(Garbage-First)垃圾回收器是一款面向服务端应用、为大内存和多处理器系统设计的革命性垃圾回收器。G1的核心设计目标是在满足高吞吐量的同时,建立一个“可…

CSS 中 overflow 属性的两个分属性 overflow-x 和 overflow-y 互相影响问题

CSS 中 overflow 属性的两个分属性 overflow-x 和 overflow-y 互相影响问题修改 CSS3 中的 overflow-x 属性,会影响同一元素的 overflow-y 属性。 举例: <div class="relative overflow-y-scroll overflow-x…

C#项目工程文件中,删除两头相同字符串,中间不一样的内容

示例: /// <para>Представляет TCP-прослушиватель, который ожидает подключения клиентов.</para>输入匹配:///\s*<para>[^<]*…

Day13显示模式

标签在网页的显示方式称为显示模式 共有三种不同的显示模式,其作用也各不相同<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="vie…

人工智能加持,海外市场无限可能!AI外呼助您轻松拓展全球业务!

在全球化竞争愈发激烈的今天,越来越多企业将目光投向海外市场。然而,真正踏出国门后才会发现,跨境业务的挑战远比想象中复杂。语言沟通障碍、时区差异、客户响应慢、人工成本高,这些都成为阻碍企业有效拓展海外客户…

从编码到部署:5大AI工具盘活你的全栈开发流程

​ 全栈开发者的日常,往往是在不同工具间不断切换。今天,我们来聊聊那些真正能提升效率的AI工具,看看它们如何各司其职,又在哪些场景下能协同作战。 一、前端原型:快速构思的得力助手 在前端构思阶段,一些AI工具…

如何是一个人工智能公司

如何是一个人工智能公司在公司业务层面,使用人工智能手段并达到了比较优秀的程度,带来了显著价值。

虚拟中间号和手机号有什么区别?

在企业通信和客户隐私保护场景中,“虚拟中间号”这个词越来越常被提及。很多企业在选择通信方案时,往往会纠结:虚拟中间号与普通手机号到底有什么区别?两者能否互换?其实,这背后牵涉的不仅仅是号码本身,更是企业…

关于OpenGL在AMD设备无法显示内容的解决方法

无任何报错,但是看不到任何渲染的东西,源程序在Intel CPU+Nv卡上没有问题。 使用的是4.3版本. 此时调试输出内容为 GL Renderer: AMD Radeon(TM) Graphics GL Version: 4.6.0 Compatibility Profile Context 25.10.2…

超越代码补全:5个能理解你项目上下文的AI编程伙伴

​ 随着AI编程工具的不断进化,它们正在从提供简单代码补全的"助手",转变为能够深度理解项目上下文、协助完成复杂工程任务的"伙伴"。今天我们将盘点5款在这方面表现突出的AI编程工具,看看它们如…

共绩算力 vscode git笔记

# git clone https://github.com/ultralytics/yolov5.git Cloning into yolov5... error: RPC failed; curl 16 Error in the HTTP2 framing layer fatal: expected flush after ref listinggit config --global http.…

WPF 的ListBox 去除默认的Item项,鼠标hover的背景颜色

一、发现的问题 1、最近在做一个新的桌面应用:多屏协同。里边的UI好多使用到了ListBox的。如下图所示 2、使用的Xmal的样式如下:<!--设备列表--><Border Grid.Row="0" Grid.Column="1"…

不止高精度!正点原子 EL15 深度解析:精度、性价比全拉满!

不止高精度!正点原子 EL15 深度解析:精度、性价比全拉满! 在电源测试、电池容量校准、元器件老化验证等场景中,电子负载是不可或缺的核心工具。但市面上同功率段产品要么精度不足,要么价格居高不下,还常存在操作…

记录Oracle数据库账号异常锁定的排查处理过程

记录Oracle数据库账号异常锁定的排查处理过程一、问题描述 因等保测评安全要求,需要设置数据库的密码安全策略,修改了密码复杂度(因原密码复杂度不够,这里修改了原密码)和密码错误锁定次数(5次)。但是策略设置生…

CF1770F Koxia and Sequence

若长度为 \(n\) 的非负整数数组 \(a\) 满足下列条件,我们称其为好数组:\(a_1 + a_2 + \dots + a_n = x\)\(a_1 \mid a_2 \mid \dots \mid a_n = y\)我们定义长度为 \(n\) 的非负整数数组 \(a\) 的权值为 \(a_1 \oplu…

问题解决:gitlab-runner 报Jobs log exceeded limit of 4194304 bytes

gitlab-runner 报Jobs log exceeded limit of 4194304 bytes 原因:gitlab-runner输出日志超过默认4kb。 解决方案:找到GitLab-runner配置文件“config.toml”,修改/新增配置“output_limit=1048576” 重启gitlab-r…

数据采集与融合技术实践2

数据采集与融合技术实践2 任务一 代码和图片 任务要求在中国气象网(http://www.weather.com.cn)给定城市集的7日天气预报,并保存在数据库。根据浏览网址观察可发现,每个城市的数据保存在http://www.weather.com.cn/w…

NOIP 模拟赛 2 总结

分数:\(100 + 30 + 50 + 20 = 200\),机房 Rank 2 T1 这道题其实很简单,但是在考场上卡了我短路的脑子很长时间。 首先,如果把这道题倒过来看,给定一个最大的丑陋值,并求解最多能匹配多少副手套,就变成了经典的 …

利用点击劫持漏洞触发XSS攻击:我是如何赚取350美元的

本文详细介绍了作者如何通过点击劫持漏洞成功触发自跨站脚本攻击的完整过程。文章深入解析了点击劫持和XSS漏洞的技术原理,展示了如何利用聊天机器人诱使用户执行恶意载荷,并最终获得350美元漏洞赏金的实战经验。我是…

人狗大战Ⅳ

核心玩法设计团队组建:玩家A和玩家B各自从「6个人类角色」中选2个,从「4种狗角色」中选1个,组成3人团队 每个角色有独特属性(生命值、攻击力、防御力、技能)回合制对战:玩家轮流操作(玩家A→玩家B→玩家A...) …