在 C++ 中,std::string 是一个非常常用的类,它提供了许多操作来处理字符串。std::string 作为 C++ 标准库的一部分,能够动态管理字符序列,并且比 C 风格的字符数组更加安全和方便。
以下是 std::string 的一些常用操作:
1. 创建和初始化字符串
std::string s1; std::string s2 = "Hello"; std::string s3("World"); std::string s4(s3); std::string s5(5, 'A');
|
2. 访问字符串中的字符
- 使用
[] 或 at() 来访问或修改字符串中的字符。
std::string s = "Hello"; char c1 = s[1]; char c2 = s.at(2); s[0] = 'J';
|
3. 拼接字符串
- 使用
+ 操作符或 append() 方法拼接字符串。
std::string s1 = "Hello"; std::string s2 = "World"; std::string s3 = s1 + " " + s2; s1.append(" Everyone");
|
4. 获取字符串的长度
- 使用
length() 或 size() 获取字符串长度(返回的类型是 std::string::size_type,等同于 size_t)。
std::string s = "Hello"; std::cout << s.length(); std::cout << s.size();
|
5. 查找子串
- 使用
find()、rfind() 来查找子串的第一次或最后一次出现位置。
std::string s = "Hello World"; size_t pos = s.find("World"); if (pos != std::string::npos) { std::cout << "Found at position: " << pos; }
size_t rpos = s.rfind("o");
|
6. 截取子串
std::string s = "Hello World"; std::string sub = s.substr(6, 5);
|
7. 插入字符串
- 使用
insert() 在指定位置插入字符或子串。
std::string s = "Hello"; s.insert(5, " World");
|
8. 删除字符串中的字符
std::string s = "Hello World"; s.erase(5, 6);
|
9. 替换字符串中的部分内容
std::string s = "Hello World"; s.replace(6, 5, "Everyone");
|
10. 比较字符串
- 使用
==、!=、<、> 等操作符,或者 compare() 函数来比较字符串。
std::string s1 = "Hello"; std::string s2 = "World";
if (s1 == s2) { std::cout << "Equal"; } else { std::cout << "Not Equal"; }
int cmp = s1.compare(s2);
|
11. 转换为 C 风格的字符串
- 使用
c_str() 方法获取 const char* 类型的 C 风格字符串。
std::string s = "Hello"; const char* c_str = s.c_str();
|
12. 遍历字符串
- 可以使用范围
for 循环或普通循环来遍历字符串。
std::string s = "Hello"; for (char c : s) { std::cout << c << " "; }
for (size_t i = 0; i < s.length(); ++i) { std::cout << s[i] << " "; }
|
13. 清空字符串
std::string s = "Hello"; s.clear();
|
14. 判断字符串是否为空
std::string s = ""; if (s.empty()) { std::cout << "String is empty"; }
|
15. 字符串的迭代器
begin() 和 end() 返回指向字符串开头和结尾的迭代器,可以使用它们进行字符串的遍历。
std::string s = "Hello"; for (auto it = s.begin(); it != s.end(); ++it) { std::cout << *it << " "; }
|
16. 字符串中的字符计数
- 使用
std::count 计算某个字符在字符串中出现的次数。
#include <algorithm> std::string s = "Hello World"; int count = std::count(s.begin(), s.end(), 'l'); std::cout << "Count of 'l': " << count;
|
17.reverse
reverse 是 C++ 标准库 <algorithm> 中的一个函数,用于反转容器中元素的顺序(如字符串、数组、向量等)。
- 头文件:必须包含
<algorithm>。
- 作用:将指定范围内的元素反转(第一个元素和最后一个元素交换,第二个和倒数第二个交换,以此类推)。
- 语法:
- 起始迭代器:指向要反转的第一个元素。
- 结束迭代器:指向要反转的最后一个元素的下一个位置(左闭右开区间)。
示例:
#include <iostream> #include <string> #include <algorithm>
using namespace std;
int main() { string s = "hello"; reverse(s.begin(), s.end()); cout << s; return 0; }
|