std::string 的使用
时间: 2023-09-07 15:16:13 浏览: 28
std::string 是 C++ 中的字符串数据类型,使用 std 命名空间来声明。而 cstring 是 C 语言中的字符串库,包含了一系列操作字符串的函数。两者的区别在于 std::string 是基于面向对象的思想设计,具有更多的操作函数和易于扩展性,而 cstring 是基于 C 语言的字符串库,使用较为繁琐,功能比较有限,但是在某些场合下使用更加方便。
相关问题
std::string 使用
std::string 是 C++ 中的一种字符串类型。它实际上是一个封装了动态字符数组的类。使用 std::string 可以轻松地进行字符串操作,如拼接、插入、删除、查找等。
使用 std::string 的方法如下:
1. 定义 std::string 变量:
```
#include <string>
std::string s; // 空字符串
std::string s1 = "Hello, world!"; // 使用字面值初始化
std::string s2(s1); // 使用另一个 std::string 初始化
std::string s3(5, 'a'); // 使用重复的字符初始化
```
2. 使用 std::string:
```
std::string s1 = "Hello, ";
std::string s2 = "world!";
std::string s3 = s1 + s2; // 使用 + 运算符拼接字符串
s1 += s2; // 使用 += 运算符拼接字符串
s1.size(); // 获取字符串的长度
s1.empty(); // 判断字符串是否为空
s1[0] = 'H'; // 修改字符串的某个位置的值
s1.find(s2); // 查找字符串中的子串
s1.substr(0, 5); // 获取字符串的子串
s1.insert(5, s2); // 在字符串的某个位置插入子串
s1.erase(5, 5); // 从字符串的某个位置开始删除子串
```
std::string 也有许多其他的方法,更多详细信息可以参考 C++ 官方文档。
std::string使用
std::string 是 C++ STL 中的一个字符串类,可以方便地进行字符串的操作。使用 std::string 需要包含头文件 <string>。
下面是一些 std::string 的常用操作:
1. 声明一个字符串变量:
```
std::string str;
```
2. 给字符串变量赋值:
```
str = "hello world";
```
3. 获取字符串长度:
```
int len = str.length();
```
4. 字符串拼接:
```
str += " from C++";
```
5. 字符串比较:
```
if (str == "hello world from C++") {
// 字符串相等
}
```
6. 获取子串:
```
std::string sub = str.substr(0, 5); // 获取从下标0开始,长度为5的子串
```
7. 查找子串:
```
size_t pos = str.find("world"); // 查找 "world" 字符串在 str 中的位置
```
以上是 std::string 的一些常用操作,还有很多其他操作可以参考 C++ STL 的官方文档。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)