string的用法
时间: 2023-09-08 22:12:13 浏览: 49
string是C++中的一个数据类型,用于表示字符串。可以通过以下方式来使用string:
1. 包含头文件string
```
#include <string>
```
2. 声明一个string变量
```
string str;
```
3. 给string变量赋值
```
str = "Hello World";
```
4. 使用string的成员函数
例如,可以使用size()函数获取字符串的长度:
```
int len = str.size();
```
还可以使用substr()函数获取子串:
```
string sub = str.substr(1, 3); // 获取从第1个字符开始,长度为3的子串
```
另外,string还支持字符串的拼接、查找、替换等操作。更多用法可以查看C++官方文档。
相关问题
String 使用方法
String 是 Java 中的一个类,用于表示字符串类型的数据。可以通过以下方法来使用 String 类:
1. 创建字符串对象:可以使用双引号或者单引号来创建一个字符串对象,例如:
String str1 = "Hello World!";
String str2 = new String("Hello World!");
2. 字符串拼接:可以使用加号来拼接两个字符串,例如:
String str3 = str1 + str2;
3. 获取字符串长度:可以使用 length() 方法来获取字符串的长度,例如:
int len = str1.length();
4. 截取字符串:可以使用 substring() 方法来截取字符串的一部分,例如:
String subStr = str1.substring(, 5);
以上就是 String 类的一些常用方法,可以根据需要灵活运用。
C++ string用法
C++中的string是一个非常方便的字符串类型,它可以动态地分配内存,可以通过下标或迭代器访问字符串中的字符,也可以进行字符串的拼接、查找、替换等操作。以下是一些常用的string用法:
1. 声明和初始化string变量:
```c++
string str1; // 声明一个空字符串
string str2 = "hello"; // 声明并初始化一个字符串
string str3("world"); // 使用构造函数声明并初始化一个字符串
```
2. 字符串的输入和输出:
```c++
string str;
cin >> str; // 从标准输入读入一个字符串
cout << str << endl; // 输出字符串到标准输出
```
3. 字符串的拼接:
```c++
string str1 = "hello";
string str2 = "world";
string str3 = str1 + " " + str2; // 使用+运算符拼接字符串
```
4. 字符串的查找和替换:
```c++
string str = "hello world";
int pos = str.find("world"); // 查找子串"world"在str中的位置
str.replace(pos, 5, "you"); // 替换子串"world"为"you"
```
5. 字符串的遍历:
```c++
string str = "hello";
for (int i = 0; i < str.size(); i++) {
cout << str[i] << endl; // 使用下标访问字符串中的字符
}
for (auto c : str) {
cout << c << endl; // 使用迭代器访问字符串中的字符
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)