stl中的string
时间: 2023-05-23 13:05:01 浏览: 61
是什么?
A:STL中的string是一个字符串类,提供了方便的字符串操作方法和功能,包括字符串的拼接、查找和替换等。使用string类型可以避免C语言中字符串处理的一些问题,比如内存管理和越界等问题。同时,string类型也可以方便的与其他STL容器(如vector、list等)配合使用,提高了代码的可读性和可维护性。
相关问题
采用STL中string类型实现将字符串中的所有"you"替换成"we"
可以使用STL中的string类型的replace函数实现将字符串中的所有"you"替换成"we",具体代码如下:
```c++
#include <string>
#include <iostream>
using namespace std;
int main() {
string str = "How are you? Are you doing well?";
string oldStr = "you";
string newStr = "we";
size_t pos = 0;
while ((pos = str.find(oldStr, pos)) != string::npos) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
cout << str << endl;
return 0;
}
```
运行结果为:
```
How are we? Are we doing well?
```
C++ STL 库中 string
在 C++ STL 库中,string 是一种标准库中的字符串类型,可以用来存储和处理字符串。string 类型提供了许多字符串操作函数,包括字符串的拼接、查找、替换、比较等。使用 string 类型可以方便地进行字符串操作,而且具有高效性和可移植性。以下是 string 类型的常用操作:
1. 创建一个 string 对象:
```
string s1; // 创建一个空字符串
string s2("hello"); // 创建一个值为 "hello" 的字符串
string s3(s2); // 使用 s2 创建一个新的字符串 s3
string s4(5, 'a'); // 创建一个含有 5 个字符 'a' 的字符串
```
2. 获取 string 对象中的字符和子串:
```
char c = s1[0]; // 获取字符串 s1 的第一个字符
string s5 = s2.substr(2, 3); // 获取字符串 s2 中从第 2 个字符开始的 3 个字符的子串
```
3. 修改 string 对象中的字符和子串:
```
s1[0] = 'h'; // 修改字符串 s1 的第一个字符为 'h'
s2.replace(1, 2, "xx"); // 将字符串 s2 中从第 1 个字符开始的 2 个字符替换为 "xx"
```
4. 连接 string 对象:
```
s1 += "world"; // 将字符串 "world" 连接到字符串 s1 的末尾
s3 = s2 + s1; // 将字符串 s1 和 s2 连接生成新的字符串 s3
```
5. 查找和比较 string 对象:
```
int pos = s2.find("el"); // 查找字符串 s2 中第一次出现 "el" 的位置
bool flag = (s1 == s2); // 判断字符串 s1 和 s2 是否相等
```
6. 转换 string 对象:
```
int x = stoi(s1); // 将字符串 s1 转换为整数类型
double y = stod(s2); // 将字符串 s2 转换为浮点数类型
```
总之,使用 string 类型可以方便地进行字符串操作,而且具有高效性和可移植性。