在C++ STL中,std::string是一种非常常用的字符串类型。虽然std::string提供了基本的字符串操作功能,但是在某些情况下,你可能会发现一些你未曾注意到的秘密。
reserve 方法:
reserve 方法可以预分配字符串容量,以减少在增加字符串长度时的内存重新分配次数。
std::string str;
str.reserve(100); // 预分配100个字符的空间
shrink_to_fit 方法:
shrink_to_fit 方法可以请求std::string释放未使用的内存。
std::string str = "Hello, World!";
str.shrink_to_fit(); // 请求释放未使用的内存
data 和 c_str 方法:
data 方法返回指向字符数组的指针,c_str 方法返回指向以空字符结尾的字符数组的指针。
std::string str = "Hello, World!";
const char* dataPtr = str.data();
const char* cStrPtr = str.c_str();
移动语义:
C++11引入了移动语义,可以高效地转移std::string中的内存所有权。
std::string createString() {
std::string str = "Hello, World!";
return str; // 移动构造函数,而不是复制
}
初始化列表:
可以使用初始化列表来初始化std::string。
std::string str = {'H', 'e', 'l', 'l', 'o'};
append 方法:
append 方法可以在字符串末尾追加字符或字符串。
std::string str = "Hello, ";
str.append("World!"); // 结果为 "Hello, World!"
find 方法:
find 方法可以用于查找子字符串。
std::string str = "Hello, World!";
size_t pos = str.find("World"); // 返回子字符串首次出现的位置
迭代器:
可以使用迭代器遍历std::string中的字符。
std::string str = "Hello, World!";
for (auto it = str.begin(); it != str.end(); ++it) {
std::cout << *it;
}
这些是std::string的一些不太常用但有时候很有用的功能。