std::string常用方法

std::string常用方法

内容

C++ 的 std::string 是标准库中用于处理字符串的核心类,提供了丰富的操作方法。以下是常用的方法分类整理,附示例代码和关键说明:


1. 构造与赋值

方法 说明 示例
string() 默认构造空字符串 string s1;
string(const char*) 从C风格字符串构造 string s2("hello");
string(size_t n, char c) 构造包含 n 个字符 c 的字符串 string s3(5, 'a'); // "aaaaa"
operator= 赋值操作 s1 = "world";

2. 容量操作

方法 说明 示例
size() / length() 返回字符数量(等价) int len = s.size();
empty() 判断是否为空字符串 if (s.empty()) { ... }
reserve(size_t n) 预分配内存(优化多次追加操作) s.reserve(100);
capacity() 返回当前分配的存储容量 int cap = s.capacity();

3. 元素访问

方法 说明 示例
operator[] 访问字符(不检查越界) char c = s[0];
at(size_t pos) 访问字符(越界抛出 out_of_range char c = s.at(1);
front() 首字符 char c = s.front();
back() 末字符 char c = s.back();

4. 修改操作

方法 说明 示例
append() 追加字符串/字符 s.append("!!");
push_back(char c) 尾部追加单个字符 s.push_back('!');
insert(pos, args) 在指定位置插入内容 s.insert(3, "xxx");
erase(pos, len) 删除从 pos 开始的 len 个字符 s.erase(2, 3);
clear() 清空字符串 s.clear();
replace(pos, len, str) 替换子串 s.replace(2, 2, "xx");

5. 字符串操作

方法 说明 示例
c_str() 返回C风格字符串(const char* printf("%s", s.c_str());
substr(pos, len) 提取子串(默认到结尾) string sub = s.substr(2, 3);
find(str, pos) 查找子串位置(返回索引或 string::npos int idx = s.find("lo");
rfind() 从后向前查找 idx = s.rfind('o');
compare(str) 比较字符串(返回0表示相等) if (s.compare("test") == 0)

6. 迭代器支持

方法 说明 示例
begin() / end() 正向迭代器 for (auto it = s.begin(); it != s.end(); ++it)
rbegin() / rend() 反向迭代器 for (auto rit = s.rbegin(); rit != s.rend(); ++rit)

7. 其他实用操作

方法 说明 示例
swap(string& other) 交换两个字符串内容 s1.swap(s2);
getline(istream&, string&) 从输入流读取一行字符串 getline(cin, s);
stoi(), stol(), stof() 字符串转数值(C++11) int num = stoi("123");

示例代码:综合用法

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "Hello";
    s.append(" World");       // "Hello World"
    s.insert(5, " C++");      // "Hello C++ World"
    s.replace(6, 3, "STL");   // "Hello STL World"
  
    size_t pos = s.find("STL");
    if (pos != string::npos) {
        cout << "Found 'STL' at position: " << pos << endl;
    }
  
    string sub = s.substr(6, 3); // "STL"
    cout << "Substring: " << sub << endl;
  
    return 0;
}

注意事项

  1. 越界访问operator[] 不检查越界,优先使用 at() 提高安全性。
  2. C风格字符串c_str() 返回的指针在字符串修改后可能失效。
  3. 性能优化:频繁拼接字符串时,使用 reserve() 预分配内存减少动态扩容开销。

建议参考 C++官方文档 深入学习更多细节。

posted @ 2025-03-12 16:17  Gold_stein  阅读(244)  评论(0)    收藏  举报