C++string类
时间: 2023-11-14 12:06:16 浏览: 55
C++中的string类是一个非常常用的字符串处理类,它属于标准库中的一部分。使用string类可以更方便地操作字符串数据,而不需要手动处理字符数组。你可以使用string类来存储、修改和操作字符串。
以下是一些常见的string类的用法示例:
1. 创建和初始化字符串:
```
string str = "Hello, world!"; // 直接赋值
string str2("Hello"); // 使用构造函数
string str3 = str.substr(0, 5); // 使用substr()函数截取子串
```
2. 字符串拼接:
```
string str = "Hello";
str += " world"; // 使用+=操作符拼接字符串
string result = str + "!"; // 使用+操作符拼接字符串
```
3. 访问字符串中的字符:
```
string str = "Hello";
char ch = str[0]; // 使用下标访问单个字符
```
4. 获取字符串长度:
```
string str = "Hello";
int length = str.length(); // 使用length()函数获取字符串长度
```
5. 查找和替换字符串:
```
string str = "Hello, world!";
size_t found = str.find("world"); // 使用find()函数查找子串
if (found != string::npos) {
str.replace(found, 5, "C++"); // 使用replace()函数替换子串
}
```
这些只是string类的一些基本用法示例,还有很多其他功能可以探索和使用。希望这些示例能帮到你!如果你有任何进一步的问题,请随时提问。
相关推荐
![h](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)