string对象
时间: 2023-07-01 08:11:11 浏览: 56
在 C++ 中,`string` 是标准库中的一个类,它表示一个字符串对象。使用 `string` 类可以方便地进行字符串的操作和处理,包括创建字符串对象、访问字符串中的字符、连接字符串、查找子串等等。
以下是一些 `string` 类的常用操作:
1. 创建字符串对象:
```cpp
string str1; // 创建一个空字符串
string str2 = "Hello, world!"; // 创建一个带有初始值的字符串
```
2. 访问字符串中的字符:
```cpp
string str = "Hello, world!";
char ch = str[0]; // 访问第一个字符
```
3. 连接字符串:
```cpp
string str1 = "Hello,";
string str2 = " world!";
string str3 = str1 + str2; // 连接两个字符串
cout << str3 << endl; // 输出 "Hello, world!"
```
4. 查找子串:
```cpp
string str = "Hello, world!";
string substr = "world";
size_t pos = str.find(substr); // 查找子串在字符串中的位置
if (pos != string::npos) {
cout << "Substring found at position " << pos << endl;
} else {
cout << "Substring not found" << endl;
}
```
需要注意的是,`string` 类中的字符串是可变的,可以通过赋值操作或者其他操作修改字符串的内容。例如:
```cpp
string str = "Hello";
str += ", world!"; // 将 ", world!" 添加到字符串末尾
cout << str << endl; // 输出 "Hello, world!"
```