【C++】字符串处理标准库函数大全

在C++中,字符串处理主要通过标准库中的std::string类以及C风格的字符串函数(如strcpystrlen等,但这些通常不推荐在C++中使用,除非有特殊需求)来进行。下面主要汇总了std::string类提供的一些常用字符串处理成员函数,以及部分C++标准库中与字符串处理相关的函数。

类别函数/成员函数描述示例
构造函数std::string()创建一个空字符串std::string emptyStr;
std::string(const char* s)使用C风格字符串s初始化std::string cStr("Hello");
std::string(const std::string& str)使用另一个字符串初始化std::string strCopy(cStr);
std::string(size_t n, char c)创建一个由n个c字符组成的字符串std::string repStr(5, 'x'); // "xxxxx"
赋值操作std::string& operator=(const char* s)使用C风格字符串赋值strCopy = "World";
std::string& operator=(const std::string& str)使用另一个字符串赋值strCopy = strCopy + "!"; // "World!"
std::string& assign(const char* s)使用C风格字符串赋值strCopy.assign("Another");
std::string& assign(size_t pos, size_t n, const std::string& str)从另一个字符串中复制子串赋值strCopy.assign(0, 5, "Example"); // "Examp"
字符串大小size_t size() const noexcept返回字符串长度size_t len = strCopy.size();
size_t length() const noexcept同上(别名)size_t len2 = strCopy.length();
bool empty() const noexcept检查字符串是否为空bool isEmpty = strCopy.empty();
访问字符串内容char& operator[](size_t pos)通过索引访问并修改字符(非const)strCopy[0] = 'B'; // "Bnother"
char operator[](size_t pos) const通过索引访问字符(const)char firstChar = strCopy[0];
const char* c_str() const noexcept返回C风格字符串的指针(const)const char* cStrPtr = strCopy.c_str();
字符串比较int compare(const std::string& str) const noexcept比较两个字符串int result = strCopy.compare("Another");
修改字符串std::string& append(const std::string& str)追加字符串strCopy.append(" string"); // "Another string"
std::string& insert(size_t pos, const std::string& str)在指定位置插入字符串strCopy.insert(7, " new "); // "Another new string"
void push_back(char c)在字符串末尾添加字符strCopy.push_back('!'); // "Another new string!"
std::string& erase(size_t pos = 0, size_t len = npos)删除子串strCopy.erase(7, 4); // "Another string!"
std::string& replace(size_t pos, size_t len, const std::string& str)替换子串strCopy.replace(7, 6, " old"); // "Another old!"
查找和子串size_t find(const std::string& str, size_t pos = 0) const noexcept查找子串位置size_t pos = strCopy.find("old");
std::string substr(size_t pos = 0, size_t len = npos) const获取子串std::string sub = strCopy.substr(7, 3); // "old"
其他标准库函数<algorithm>提供字符串处理算法(如查找、替换、排序)std::sort(strCopy.begin(), strCopy.end());(假设可排序)
<sstream>字符串流,支持字符串的输入输出操作std::stringstream ss; ss << "123"; int num; ss >> num;
<regex>正则表达式库,用于复杂字符串匹配、搜索、替换std::regex e("(\\d+)"); std::smatch m; std::string target = "abc123xyz"; std::regex_search(target, m, e);

请注意,<algorithm>中的函数如std::sort通常不直接用于std::string排序(因为字符串已经是有序字符的集合),但可用于字符数组或更复杂的字符串处理场景。此外,示例中std::sort(strCopy.begin(), strCopy.end());的调用假设了一种不常见的场景,实际上并不适用于std::string,因为std::string中的字符已经是有序的(按字典顺序)。这里只是为了展示算法库如何与字符串相关容器交互。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值