在C++中,字符串处理主要通过标准库中的std::string
类以及C风格的字符串函数(如strcpy
, strlen
等,但这些通常不推荐在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
中的字符已经是有序的(按字典顺序)。这里只是为了展示算法库如何与字符串相关容器交互。