string类型 cpp 函数
时间: 2025-09-02 12:20:36 AIGC 浏览: 12
C++ 中 `string` 类型提供了丰富的函数,以下是一些常用函数的介绍:
### 构造和初始化相关函数
- `string()`:使用默认构造函数创建一个空字符串。
- `string(const char* s)`:用 C 风格的字符串构造。
- `string(size_t count, char ch)`:从给定数量的重复字符构造。
- `string(const string& other)`:复制构造,从另一个字符串复制得到新字符串。
- `string(const char* s, size_t n)`:取 C 风格字符串的前 `n` 个字符构造。
- `string(const string& str, size_t pos, size_t len = npos)`:从 `str` 的第 `pos` 个字符开始,取长度为 `len` 的子串构造(若 `len` 为 `npos`,则取到字符串末尾)。
示例代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1; // 默认构造,创建空字符串
string s2("Hello"); // 从 C 风格字符串构造
string s2_1("Hello", 3); // 前三个字符
string s2_2("Hello", 2, 3); // 从第三个开始,长度为三
string s3(10, 'x'); // 从 10 个字符 'x' 构造
string s4 = s2; // 将 s2 复制给 s4
string s5(s2, 3); // 从 s2 的第四个字符到最后
string s5_1(s2, 2, 2); // 从 s2 的第三个字符开始,长度为 2
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s2_1: " << s2_1 << endl;
cout << "s2_2: " << s2_2 << endl;
cout << "s3: " << s3 << endl;
cout << "s4: " << s4 << endl;
cout << "s5: " << s5 << endl;
cout << "s5_1: " << s5_1 << endl;
return 0;
}
```
### 插入和删除相关函数
- `insert(size_t pos, const string& str)`:在指定位置 `pos` 插入字符串 `str`。
- `erase(size_t pos = 0, size_t len = npos)`:从位置 `pos` 开始删除长度为 `len` 的子串(若 `len` 为 `npos`,则删除到字符串末尾)。
示例代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
void Test5() {
string s1("Hello World!");
s1.insert(2, "##");
cout << s1 << endl; // 输出: He##llo World!
string s2("Hello World!");
s2.erase(4, 6);
cout << s2 << endl; // 输出: Helld!
}
int main() {
Test5();
return 0;
}
```
### 比较相关函数
- `compare(const string& str)`:字符串大小比较。原理是两个字符串自左向右逐个字符相比(按 ASCII 值大小相比较),直到出现不同的字符或遇 `'\0'` 为止。若当前字符串大于 `str`,返回 1;若相等,返回 0;若小于,返回 -1。
示例代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
void Test6() {
string s1("abcd");
string s2("aBcd");
// s1 与 s2 相比第二个字符 b 的 ASCII 值大于 B
cout << s1.compare(s2) << endl; // s1 > s2 所以输出 1
}
int main() {
Test6();
return 0;
}
```
### 输入输出相关函数
- `operator>>`:输入运算符重载,可以直接对字符串进行输入。
- `operator<<`:输出运算符重载,可以直接对字符串进行输出。
- `getline(istream& is, string& str)`:获取一行字符串,`cin` 输入时默认空格是作为结束分隔,所以可以用 `getline` 将包含空格的内容输入到字符串中。
示例代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
void Test6() {
string s3;
cin >> s3;
cout << "s3: " << s3 << endl;
string s4;
getline(cin, s4);
cout << "s4: " << s4 << endl;
}
int main() {
Test6();
return 0;
}
```
阅读全文
相关推荐


















