string

概念

可以代替传统的char数组。

主要特点

  1. 动态大小string 是一个动态大小的字符序列,能够根据需要自动调整大小。
  2. 标准字符集string 默认使用 ASCII 字符集,但也支持 Unicode。
  3. 丰富的接口string 提供了丰富的成员函数和操作符,用于处理字符串的各种操作。
  4. 内存管理string 自动管理其所需的内存,因此无需手动分配或释放内存。

基本用法

1. 创建和初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <iostream>

using namespace std;

int main() {
string s1; // 创建一个空的 string
string s2 = "Hello"; // 使用字符串字面值初始化
string s3("World"); // 使用构造函数初始化
string s4 = s2 + " " + s3; // 字符串连接

cout << s4 << endl; // 输出: Hello World

return 0;
}


2. 字符串操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <string>
#include <iostream>

using namespace std;

int main() {
string s = "Hello World";

// 访问单个字符
cout << s[0] << endl; // 输出: H
cout << s.at(1) << endl; // 输出: e

// 子字符串
string sub = s.substr(6, 5); // 从位置 6 开始,长度为 5 的子字符串
cout << sub << endl; // 输出: World

// 查找子字符串
size_t pos = s.find("World");
if (pos != string::npos) {
cout << "Found at position: " << pos << endl;
}

// 替换子字符串
s.replace(6, 5, "C++");
cout << s << endl; // 输出: Hello C++

// 删除子字符串
s.erase(6, 3); // 从位置 6 开始,删除长度为 3 的子字符串
cout << s << endl; // 输出: Hello C

return 0;
}

3. 字符串的比较和拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <iostream>

using namespace std;

int main() {
string s1 = "Hello";
string s2 = "World";

// 比较字符串
if (s1 == "Hello") {
cout << "s1 is Hello" << endl;
}

if (s1 < s2) {
cout << "s1 is less than s2" << endl;
}

// 拼接字符串
string s3 = s1 + " " + s2;
cout << s3 << endl; // 输出: Hello World

return 0;
}

常用成员函数

  • 基本操作

    • size():返回字符串的长度。
    • length():返回字符串的长度(与 size() 等效)。
    • empty():检查字符串是否为空,返回布尔值。
    • clear():清空字符串。
  • 字符访问

    • operator[]:访问指定位置的字符。
    • at(size_t pos):访问指定位置的字符,带边界检查。
    • front():返回第一个字符的引用。
    • back():返回最后一个字符的引用。
  • 子字符串和查找

    • substr(size_t pos = 0, size_t len = npos):返回从 pos 开始长度为 len 的子字符串。
    • find(const string& str, size_t pos = 0):查找子字符串 str,返回第一次出现的位置,如果未找到返回 string::npos
    • rfind(const string& str, size_t pos = npos):从后向前查找子字符串 str,返回最后一次出现的位置,如果未找到返回 string::npos
    • replace(size_t pos, size_t len, const string& str):替换从 pos 开始长度为 len 的子字符串为 str
    • erase(size_t pos = 0, size_t len = npos):从 pos 开始删除长度为 len 的子字符串。
  • 拼接和转换

    • append(const string& str):在字符串末尾追加 str
    • insert(size_t pos, const string& str):在 pos 位置插入 str
    • to_string():将其他类型转换为字符串(需要包含 <string> 头文件)。

string
http://pikachuxpf.github.io/posts/9ebeb2a9/
作者
Pikachu_fpx
发布于
2024年7月23日
许可协议