目录
[string 的定义方式](#string 的定义方式)
[string 的插入](#string 的插入)
[尾插 push_back](#尾插 push_back)
[指定位置插入 insert](#指定位置插入 insert)
[string 的拼接 append](#string 的拼接 append)
[string 的删除](#string 的删除)
[尾删 pop_back](#尾删 pop_back)
[指定位置删除 erase](#指定位置删除 erase)
[string 的查找](#string 的查找)
[正向查找 find](#正向查找 find)
[反向查找 rfind](#反向查找 rfind)
[string 的比较 compare](#string 的比较 compare)
[string 的替换 replace](#string 的替换 replace)
[string 的交换 swap](#string 的交换 swap)
[string 的大小和容量](#string 的大小和容量)
[string 中元素的访问](#string 中元素的访问)
[\[\] 运算符](#[] 运算符)
[at() 方法(带边界检查)](#at() 方法(带边界检查))
[范围 for](#范围 for)
[string 中运算符的使用](#string 中运算符的使用)
[= 赋值](#= 赋值)
[+= 追加](#+= 追加)
[+ 连接(返回新对象)](#+ 连接(返回新对象))
[>> / << 输入输出](#>> / << 输入输出)
[string 与 C 字符串的转换](#string 与 C 字符串的转换)
[C字符串 → string](#C字符串 → string)
[string → C字符串](#string → C字符串)
[copy() 复制到字符数组(不自动加 '\0')](#copy() 复制到字符数组(不自动加 '\0'))
[getline 读取含空格的整行](#getline 读取含空格的整行)
string 的定义方式
string 类提供了多种构造函数,常用形式如下:
| 构造函数 | 说明 |
|---|---|
string() |
构造空字符串 |
string(const char* s) |
复制 C 风格字符串 s |
string(const char* s, size_t n) |
复制 s 的前 n 个字符 |
string(size_t n, char c) |
生成 n 个 c 字符组成的字符串 |
string(const string& str) |
拷贝构造 |
string(const string& str, size_t pos, size_t len = npos) |
从 str 的 pos 位置开始,复制 len 个字符 |
示例:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1; // 空字符串
string s2("Hello C++"); // 复制 "Hello C++"
string s3("Hello C++", 5); // 复制前5个字符 -> "Hello"
string s4(8, '*'); // 8个 '*' -> "********"
string s5(s2); // 拷贝 s2
string s6(s2, 6, 3); // 从索引6开始复制3个字符 -> "C++"
cout << s1 << endl; // (空)
cout << s2 << endl; // Hello C++
cout << s3 << endl; // Hello
cout << s4 << endl; // ********
cout << s5 << endl; // Hello C++
cout << s6 << endl; // C++
return 0;
}
string 的插入
尾插 push_back
cpp
string s;
s.push_back('A');
s.push_back('B');
s.push_back('C');
cout << s << endl; // ABC
指定位置插入 insert
cpp
string s("Data");
s.insert(4, "Base"); // "Data" + "Base" -> "DataBase"
cout << s << endl; // DataBase
string t("Struct");
s.insert(4, t); // "Data" + "Struct" + "Base" -> "DataStructBase"
cout << s << endl; // DataStructBase
s.insert(s.end(), '!'); // 末尾插入字符
cout << s << endl; // DataStructBase!
string 的拼接 append
cpp
string s1("C++");
string s2(" Programming");
s1.append(s2); // "C++ Programming"
s1.append(" is fun"); // "C++ Programming is fun"
s1.append(3, '!'); // "C++ Programming is fun!!!"
cout << s1 << endl;
string 的删除
尾删 pop_back
cpp
string s("Hello!");
s.pop_back(); // "Hello"
s.pop_back(); // "Hell"
cout << s << endl;
指定位置删除 erase
cpp
string s("I love Python and C++");
s.erase(7, 6); // 删除 "Python" -> "I love and C++"
s.erase(7, 1); // 删除多余空格 -> "I love and C++"
s.erase(s.begin(), s.begin()+5); // 删除 "I lov" -> "e and C++"
cout << s << endl;
string 的查找
正向查找 find
cpp
string url("https://en.cppreference.com/w/cpp/string/basic_string");
string sub("cpp");
size_t pos1 = url.find(sub);
cout << pos1 << endl; // 8
size_t pos2 = url.find("reference");
cout << pos2 << endl; // 20
size_t pos3 = url.find(':');
cout << pos3 << endl; // 5
反向查找 rfind
cpp
string text("alpha beta alpha gamma");
string word("alpha");
size_t pos1 = text.rfind(word);
cout << pos1 << endl; // 11
size_t pos2 = text.rfind("beta");
cout << pos2 << endl; // 6
size_t pos3 = text.rfind('a');
cout << pos3 << endl; // 13
string 的比较 compare
比较规则:
-
返回
0:相等 -
返回
<0:当前字符串小于参数 -
返回
>0:当前字符串大于参数
cpp
string s1("apple");
string s2("banana");
cout << s1.compare(s2) << endl; // -1 (apple < banana)
// 比较 s1 从索引1开始的3个字符("ppl") 与 s2
cout << s1.compare(1, 3, s2) << endl; // -1
// 比较 s1[0..3]("appl") 与 s2[0..3]("bana")
cout << s1.compare(0, 4, s2, 0, 4) << endl; // -1
string 的替换 replace
cpp
string s("I like Java");
s.replace(7, 4, "C++"); // 将"Java"替换为"C++" -> "I like C++"
cout << s << endl;
s.replace(10, 1, 3, '!'); // 将最后一个字符替换为三个'!' -> "I like C++!!!"
cout << s << endl;
string 的交换 swap
cpp
string a("Hello");
string b("World");
a.swap(b); // 成员函数交换
cout << a << " " << b << endl; // World Hello
swap(a, b); // 非成员函数交换
cout << a << " " << b << endl; // Hello World
string 的大小和容量
| 函数 | 说明 |
|---|---|
size() / length() |
返回有效字符个数 |
max_size() |
最大可容纳字符数(平台相关) |
capacity() |
当前分配的存储空间大小 |
resize(n, c) |
改变有效字符数为 n,多出的用 c 填充 |
reserve(n) |
预留至少 n 个字符的容量 |
clear() |
清空内容 |
empty() |
判断是否为空 |
示例:
cpp
string s("C++");
cout << s.size() << " " << s.capacity() << endl; // 3 15
s.resize(10, '-');
cout << s << " " << s.size() << endl; // C++------- 10
s.reserve(50);
cout << s.capacity() << endl; // 63 (或更大)
s.clear();
cout << s.empty() << endl; // 1
string 中元素的访问
[] 运算符
cpp
string s("C++11");
for (size_t i = 0; i < s.size(); i++) {
s[i] = toupper(s[i]); // 转为大写
}
cout << s << endl; // C++11 (注意 '+' 不会变)
at() 方法(带边界检查)
cpp
string s("STL");
for (size_t i = 0; i < s.size(); i++) {
s.at(i) = tolower(s.at(i));
}
cout << s << endl; // stl
范围 for
cpp
string s("C++");
for (char& ch : s) {
ch = ch + 1; // 每个字符 ASCII +1
}
cout << s << endl; // D++ (C->D, + -> , 第二个+也变)
迭代器
cpp
string s("Hello");
for (auto it = s.begin(); it != s.end(); ++it) {
*it = *it + 1;
}
cout << s << endl; // Ifmmp
string 中运算符的使用
= 赋值
cpp
string s1, s2("C++"), s3;
s1 = s2; // string 赋值
s1 = "Python"; // C 字符串赋值
s1 = 'J'; // 字符赋值
+= 追加
cpp
string s("Hello");
s += " ";
s += "World";
s += '!';
cout << s << endl; // Hello World!
+ 连接(返回新对象)
cpp
string a("C++"), b("11");
string c = a + b; // "C++11"
string d = a + " and " + b; // "C++ and 11"
string e = "Version " + a; // "Version C++"
>> / << 输入输出
cpp
string s;
cin >> s; // 遇空白停止
cout << s;
关系运算符(按字典序)
cpp
string s1("abc"), s2("abd");
cout << (s1 < s2) << endl; // 1
cout << (s1 == "abc") << endl; // 1
迭代器相关函数
正向迭代器
cpp
string s("Forward");
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it;
}
cout << endl; // Forward
反向迭代器
cpp
string s("Reverse");
for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
cout << *rit;
}
cout << endl; // esreveR
string 与 C 字符串的转换
C字符串 → string
cpp
const char* cstr = "Hello C++";
string s(cstr); // 直接构造
string → C字符串
cpp
string s("Hello C++");
const char* cstr1 = s.c_str(); // 返回 const char*,以 '\0' 结尾
const char* cstr2 = s.data(); // C++11 后与 c_str() 相同
cout << cstr1 << endl;
提取子字符串
substr()
cpp
string full("2025-03-30");
string year = full.substr(0, 4); // "2025"
string month = full.substr(5, 2); // "03"
string day = full.substr(8); // "30"
cout << year << "-" << month << "-" << day << endl;
copy() 复制到字符数组(不自动加 '\0')
cpp
string s("abcdef");
char buffer[10];
size_t len = s.copy(buffer, 3, 2); // 从索引2开始复制3个字符 -> "cde"
buffer[len] = '\0';
cout << buffer << endl; // cde
getline 读取含空格的整行
默认以换行符分隔
cpp
string line;
cout << "Enter a sentence: ";
getline(cin, line); // 输入 "Hello C++ World"
cout << line << endl; // 输出 "Hello C++ World"
指定分隔符
cpp
string data;
getline(cin, data, ','); // 输入 "apple,banana,orange"
cout << data << endl; // 输出 "apple"