cpp中string中的方法
时间: 2024-06-07 07:11:42 浏览: 1
C++中的string类提供了丰富的方法,下面是一些常用的方法:
1. `length()`:获取字符串的长度。
2. `size()`:同`length()`,获取字符串的长度。
3. `empty()`:判断字符串是否为空。
4. `clear()`:清空字符串。
5. `append()`:在字符串末尾添加字符或字符串。
6. `insert()`:在指定位置插入字符或字符串。
7. `erase()`:删除指定位置的字符或一段字符。
8. `replace()`:替换指定位置的字符或一段字符。
9. `substr()`:截取子字符串。
10. `find()`:查找指定字符或字符串,并返回其位置。
11. `rfind()`:从后往前查找指定字符或字符串,并返回其位置。
12. `compare()`:比较两个字符串。
13. `c_str()`:将字符串转换为C风格字符串。
14. `data()`:获取字符串内部的字符数组。
15. `operator[]`:访问字符串中指定位置的字符。
相关问题
cpp中string类怎么用
在C++中,String类是一个非常有用的字符串处理工具,提供了许多方便的方法和操作。下面是一些常见的String类用法:
1. 声明和初始化一个字符串对象:
```cpp
string str = "Hello World!";
```
2. 获取字符串长度:
```cpp
int len = str.length();
```
3. 获取字符串的子串:
```cpp
string sub_str = str.substr(0, 5); //获取从下标0开始,长度为5的子串
```
4. 字符串拼接:
```cpp
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2;
```
5. 字符串查找:
```cpp
int pos = str.find("World"); //查找子串"World"在str中的位置
```
6. 字符串替换:
```cpp
str.replace(pos, 5, "China"); //从pos位置开始,替换长度为5的子串为"China"
```
7. 字符串比较:
```cpp
string str1 = "Hello";
string str2 = "World";
if (str1 == str2) {
//字符串相等
} else {
//字符串不相等
}
```
这些是一些常用的String类用法,您可以根据需要选择使用。
cpp中string字符串转小写
可以使用标准库中的 `std::transform` 函数和 `std::tolower` 函数来实现将字符串转为小写的功能。具体代码如下:
```cpp
#include <algorithm>
#include <cctype>
#include <string>
std::string toLowerCase(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::tolower(c); });
return result;
}
```
使用示例:
```cpp
std::string str = "Hello World";
std::string lower_str = toLowerCase(str);
// lower_str 的值为 "hello world"
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)