C++ string 的使用方式详解
C++ 中的 std::string
是C++标准库中提供的一个类,用于处理和操作字符串。相比于C语言的字符数组,std::string
提供了更为方便和安全的字符串操作功能。以下是 C++ std::string
的使用方式详解:
1. 引入头文件
要使用 std::string
,需要包含头文件:
#include <string>
2. 初始化和赋值
可以通过多种方式初始化或赋值 std::string
:
#include <iostream>
#include <string>
int main() {
std::string s1; // 默认构造函数,生成空字符串
std::string s2("Hello, World!"); // 用C字符串初始化
std::string s3(s2); // 拷贝构造
std::string s4 = "C++"; // 用字符串字面值赋值
s1 = s2; // 使用赋值运算符
s1 = "New String"; // 用字符串字面值赋值
std::cout << s1 << std::endl;
return 0;
}
3. 基本操作
3.1 访问字符
可以使用索引或 at()
方法访问字符串中的字符:
std::string s = "Hello";
char c1 = s[1]; // 'e'
char c2 = s.at(1); // 'e', at() 方法会进行边界检查
3.2 拼接字符串
使用 +
或 +=
运算符拼接字符串:
std::string s1 = "Hello, ";
std::string s2 = "World!";
std::string s3 = s1 + s2; // "Hello, World!"
s1 += s2; // "Hello, World!"
3.3 比较字符串
可以使用标准比较运算符:
if (s1 == s2) {
// 相等
}
if (s1 != s2) {
// 不等
}
if (s1 < s2) {
// 字典序比较
}
3.4 获取长度
使用 length()
或 size()
方法:
std::string s = "Hello";
size_t len = s.length(); // 或 size(),都返回 5
3.5 查找和替换
使用 find()
、rfind()
、replace()
等方法:
std::string s = "Hello, World!";
size_t pos = s.find("World"); // 查找子字符串 "World",返回索引
s.replace(pos, 5, "C++"); // 将 "World" 替换为 "C++"
3.6 截取子串
使用 substr()
方法:
std::string s = "Hello, World!";
std::string sub = s.substr(7, 5); // 从位置 7 开始截取 5 个字符,结果为 "World"
3.7 插入与删除
使用 insert()
和 erase()
方法:
std::string s = "Hello!";
s.insert(5, ", World"); // 插入子串,结果为 "Hello, World!"
s.erase(5, 7); // 从位置 5 开始删除 7 个字符,结果为 "Hello"
4. 遍历字符串
可以使用范围循环或迭代器:
std::string s = "Hello";
for (char c : s) {
std::cout << c << ' ';
}
for (auto it = s.begin(); it != s.end(); ++it) {
std::cout << *it << ' ';
}
5. 常用其他方法
empty()
: 检查字符串是否为空。clear()
: 清空字符串内容。c_str()
: 返回指向字符串数据的 C 风格字符串的指针。
6. 特性与注意事项
std::string
自动管理内存,避免手动分配和释放内存。- 支持 Unicode 字符,但处理宽字符或 UTF-8 字符串时需特别注意字符编码和宽度。
- 边界检查:尽量使用
at()
方法以确保安全。
通过 std::string
类的强大功能,处理字符串在 C++ 中变得方便和安全。