03-进阶基础/02-字符串:修订间差异
跳转到导航
跳转到搜索
->Importer 批量导入三三文档 |
小 导入1个版本 |
(没有差异)
| |
2026年5月20日 (三) 18:12的最新版本
string 类型
C++ 提供了 string 类型来处理字符串,使用前需要 #include <string>(万能头文件已包含)。
定义与初始化
string s; // 空字符串
string s = "hello"; // 用字符串字面量初始化
string s(5, 'a'); // "aaaaa",5 个 'a'
string s = t; // 用另一个 string 初始化
基本操作
| 操作 | 说明 |
|---|---|
s.length() / s.size()
|
获取字符串长度 |
s[i]
|
访问第 [math]\displaystyle{ i }[/math] 个字符([math]\displaystyle{ 0 }[/math] 起始) |
s += t
|
在末尾拼接字符串 t
|
s == t
|
判断两个字符串是否相等 |
s < t
|
按字典序比较大小 |
s.clear()
|
清空字符串 |
s.empty()
|
判断字符串是否为空 |
遍历字符串
// 下标遍历
for (int i = 0; i < s.length(); i++)
cout << s[i];
// 范围 for
for (char c : s)
cout << c;
substr 取子串
string s = "abcdefg";
string t = s.substr(2, 3); // "cde",从下标 2 开始取 3 个字符
string u = s.substr(3); // "defg",从下标 3 取到末尾
find 查找子串
string s = "hello world";
int pos = s.find("world"); // 返回 6
if (pos == string::npos)
cout << "未找到";
字符串与数字的转换
string s = "123";
int x = stoi(s); // 字符串转 int
long long y = stoll(s); // 字符串转 long long
double d = stod(s); // 字符串转 double
string t = to_string(123); // 数字转字符串
读入空格分隔的字符串
string s;
cin >> s; // 读入一个单词(遇到空格/换行停止)
读入一整行
string s;
getline(cin, s); // 读入一整行(包括空格)
常用字符判断函数
需要 #include <cctype>(万能头已包含):
| 函数 | 说明 |
|---|---|
isdigit(c)
|
是否是数字 '0'~'9'
|
isalpha(c)
|
是否是字母 |
islower(c)
|
是否是小写字母 |
isupper(c)
|
是否是大写字母 |
tolower(c)
|
转换为小写 |
toupper(c)
|
转换为大写 |