string对象的基本编程操作代码
时间: 2024-03-18 07:42:28 浏览: 19
以下是一些string对象的基本编程操作代码:
1. 创建一个空的string对象:
```
string str;
```
2. 创建一个指定字符串的string对象:
```
string str = "Hello, World!";
```
3. 连接两个string对象:
```
string str1 = "Hello, ";
string str2 = "World!";
string result = str1 + str2; // result = "Hello, World!"
```
4. 获取string对象的长度:
```
string str = "Hello, World!";
int len = str.length(); // len = 13
```
5. 截取string对象中的子串:
```
string str = "Hello, World!";
string sub = str.substr(0, 5); // sub = "Hello"
```
6. 查找string对象中的子串:
```
string str = "Hello, World!";
int pos = str.find("World"); // pos = 7
```
7. 替换string对象中的子串:
```
string str = "Hello, World!";
str.replace(7, 5, "China"); // str = "Hello, China!"
```
8. 将string对象转换为C风格的字符串:
```
string str = "Hello, World!";
const char* cstr = str.c_str();
```
9. 将C风格的字符串转换为string对象:
```
const char* cstr = "Hello, World!";
string str = cstr;
```