查看“︁03-进阶基础/02-字符串”︁的源代码
←
03-进阶基础/02-字符串
跳转到导航
跳转到搜索
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== <code>string</code> 类型 == C++ 提供了 <code>string</code> 类型来处理字符串,使用前需要 <code>#include <string></code>(万能头文件已包含)。 === 定义与初始化 === <syntaxhighlight lang="cpp"> string s; // 空字符串 string s = "hello"; // 用字符串字面量初始化 string s(5, 'a'); // "aaaaa",5 个 'a' string s = t; // 用另一个 string 初始化 </syntaxhighlight> === 基本操作 === {| class="wikitable" ! 操作 !! 说明 |- | <code>s.length()</code> / <code>s.size()</code> | 获取字符串长度 |- | <code>s[i]</code> | 访问第 <math>i</math> 个字符(<math>0</math> 起始) |- | <code>s += t</code> | 在末尾拼接字符串 <code>t</code> |- | <code>s == t</code> | 判断两个字符串是否相等 |- | <code>s < t</code> | 按字典序比较大小 |- | <code>s.clear()</code> | 清空字符串 |- | <code>s.empty()</code> | 判断字符串是否为空 |} === 遍历字符串 === <syntaxhighlight lang="cpp"> // 下标遍历 for (int i = 0; i < s.length(); i++) cout << s[i]; // 范围 for for (char c : s) cout << c; </syntaxhighlight> === <code>substr</code> 取子串 === <syntaxhighlight lang="cpp"> string s = "abcdefg"; string t = s.substr(2, 3); // "cde",从下标 2 开始取 3 个字符 string u = s.substr(3); // "defg",从下标 3 取到末尾 </syntaxhighlight> === <code>find</code> 查找子串 === <syntaxhighlight lang="cpp"> string s = "hello world"; int pos = s.find("world"); // 返回 6 if (pos == string::npos) cout << "未找到"; </syntaxhighlight> === 字符串与数字的转换 === <syntaxhighlight lang="cpp"> 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); // 数字转字符串 </syntaxhighlight> === 读入空格分隔的字符串 === <syntaxhighlight lang="cpp"> string s; cin >> s; // 读入一个单词(遇到空格/换行停止) </syntaxhighlight> === 读入一整行 === <syntaxhighlight lang="cpp"> string s; getline(cin, s); // 读入一整行(包括空格) </syntaxhighlight> === 常用字符判断函数 === 需要 <code>#include <cctype></code>(万能头已包含): {| class="wikitable" ! 函数 !! 说明 |- | <code>isdigit(c)</code> | 是否是数字 <code>'0'~'9'</code> |- | <code>isalpha(c)</code> | 是否是字母 |- | <code>islower(c)</code> | 是否是小写字母 |- | <code>isupper(c)</code> | 是否是大写字母 |- | <code>tolower(c)</code> | 转换为小写 |- | <code>toupper(c)</code> | 转换为大写 |} [[Category:进阶基础]] [[Category:三三文档]]
返回
03-进阶基础/02-字符串
。
导航菜单
个人工具
登录
命名空间
页面
讨论
大陆简体
查看
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
特殊页面
工具
链入页面
相关更改
页面信息