《C++探幽:STL(String类的使用)》
作者的个人gitee▶️
作者的算法讲解主页每日一言:“山高自有行路客,水深亦有渡船人。🌸🌸”
概述:std::string
的用法
取自:cplusplus.com/reference/string/string/
String类可以使用的成员函数非常多,这里仅列举一些比较常用的成员函数。
🔴1. 构造函数
std::string
提供了多种构造方式:
-
默认构造:创建一个空字符串。
std::string s1;
-
从 C 风格字符串构造:将 C 风格字符串转换为
std::string
。const char* cstr = "Hello, World!"; std::string s2(cstr);
-
从另一个字符串构造:可以指定子字符串的范围。
std::string s3(s2, 7, 5); // 从 s2 的第 7 个字符开始,取 5 个字符,结果为 "World"
-
重复字符构造:指定字符和重复次数。
std::string s4(5, 'a'); // 结果为 "aaaaa"
🔴2. 字符串拼接
std::string
支持使用 +
和 +=
操作符进行拼接。
std::string s1 = "Hello";
std::string s2 = "World";
std::string s3 = s1 + ", " + s2 + "!";
s1 += " C++"; // s1 现在为 "Hello C++"
🔴3. 字符串比较
std::string
支持使用比较操作符(==
、!=
、<
、>
、<=
、>=
)进行比较。
std::string s1 = "apple";
std::string s2 = "banana";
std::string s3 = "apple";
if (s1 == s3) {
std::cout << "s1 和 s3 相等" << std::endl;
}
if (s1 < s2) {
std::cout << "s1 小于 s2" << std::endl;
}
🔴4. 访问字符
可以通过下标操作符 []
或成员函数 at()
访问字符串中的字符。
std::string s = "Hello";
char c1 = s[0]; // c1 为 'H'
char c2 = s.at(1); // c2 为 'e'
// 修改字符
s[0] = 'h'; // s 现在为 "hello"
🔴5. 字符串长度和大小
size()
:返回字符串的长度(字符数)。length()
:与size()
功能相同。empty()
:判断字符串是否为空。
std::string s = "Hello";
std::cout << "长度: " << s.size() << std::endl; // 输出 5
std::cout << "是否为空: " << s.empty() << std::endl; // 输出 0 (false)
🔴6. 子字符串操作
substr()
:提取子字符串。
std::string s = "Hello, World!";
std::string sub = s.substr(7, 5); // 从第 7 个字符开始,取 5 个字符,结果为 "World"
🔴7. 查找和替换
find()
:查找子字符串的位置。replace()
:替换子字符串。
std::string s = "Hello, World!";
size_t pos = s.find("World"); // 返回 7
if (pos != std::string::npos) {
s.replace(pos, 5, "C++"); // 将 "World" 替换为 "C++"
std::cout << s << std::endl; // 输出 "Hello, C++!"
}
🔴8. 字符串转换
c_str()
:将std::string
转换为 C 风格字符串。std::to_string()
:将数字转换为字符串。
std::string s = "Hello";
const char* cstr = s.c_str(); // C 风格字符串
int num = 42;
std::string num_str = std::to_string(num); // 将数字转换为字符串
🔴9. 字符串流
可以使用 std::stringstream
来方便地进行字符串的格式化和解析。
#include <sstream>
std::stringstream ss;
ss << "Hello" << ", " << 42 << "!";
std::string result = ss.str(); // result 为 "Hello, 42!"
// 解析字符串
std::string word;
int num;
std::stringstream("Hello 42") >> word >> num; // word 为 "Hello",num 为 42
🔴10. 常用的成员函数
clear()
:清空字符串。resize()
:调整字符串大小。append()
:追加字符串。erase()
:删除字符。
std::string s = "Hello";
s.clear(); // 清空字符串,s 现在为空
s.resize(10, 'x'); // 调整大小,不足部分用 'x' 填充,s 现在为 "Helloxxxxx"
s.append(", World!"); // 追加字符串,s 现在为 "Helloxxxxx, World!"
s.erase(5, 5); // 删除从第 5 个字符开始的 5 个字符,s 现在为 "Hello, World!"
如有错误,恳请指正。