c++ string类
时间: 2023-11-18 17:52:49 浏览: 102
C++中的string类是一个非常常用的字符串处理类,它可以方便地进行字符串的拼接、查找、替换等操作。string类的实现基于动态数组,因此可以根据需要动态地调整字符串的长度。
string类的常用方法包括:
1. length():返回字符串的长度。
2. append():将一个字符串或字符序列添加到当前字符串的末尾。
3. find():在字符串中查找指定的子串,并返回其位置。
4. replace():将指定的子串替换为另一个字符串或字符序列。
5. substr():返回从指定位置开始的指定长度的子串。
例如,以下代码演示了如何使用string类进行字符串拼接和替换操作:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "world";
string str3 = "C++";
// 字符串拼接
string result = str1 + " " + str2 + ", " + str3 + "!";
cout << result << endl;
// 字符串替换
result.replace(6, 5, "everyone");
cout << result << endl;
return 0;
}
```
输出结果为:
```
Hello world, C++!
Hello everyone, C++!
```
阅读全文
相关推荐













