1、字符串中寻找子串
可以string类中的find函数
int find(const& string str,int pos=0):从pos开始,string中寻找字符串为str的子字符串的起始位置,如果没找到,则返回-1

输出:2
2、字符串中在指定位置替换字符串
可以string类中的replace函数
string& replace(int pos, int n, const string& str): 从pos开始,连续n个字符替换成str

输出结果:你好世界 \n 你好世界
3、提取子字符串
用于提取子字符串的成员函数,它可以从原字符串中截取一部分内容创建一个新的字符串,时间复杂度是 O(n),其中 n 是要复制的子字符串的长度(即 len 参数的值)
string substr(size_t pos = 0, size_t len = npos) const;
返回一个包含从 pos 开始、长度为 len 的子字符串的新 string 对象。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 从位置7开始提取子字符串
std::string sub1 = str.substr(7);
std::cout << sub1 << std::endl; // 输出: World!
// 从位置0开始提取5个字符
std::string sub2 = str.substr(0, 5);
std::cout << sub2 << std::endl; // 输出: Hello
return 0;
}

被折叠的 条评论
为什么被折叠?



