c++中string的back()函数
时间: 2024-01-24 14:17:23 浏览: 33
在C++中,string类提供了一个名为back()的成员函数,该函数返回字符串中最后一个字符的引用(即字符串的末尾字符)。如果字符串为空,则该函数的行为是未定义的。以下是back()函数的示例用法:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
char last_char = str.back();
std::cout << "The last character of the string is: " << last_char << std::endl;
return 0;
}
```
输出结果为:
```
The last character of the string is: d
```
相关问题
C++string类库函数
C++的string类库提供了很多函数来处理和操作字符串。以下是一些常用的string类库函数:
1. length() / size():返回字符串的长度。
```
string str = "Hello";
int len = str.length(); // 或者使用 str.size();
```
2. empty():检查字符串是否为空。
```
string str = "Hello";
bool isEmpty = str.empty();
```
3. clear():清空字符串内容。
```
string str = "Hello";
str.clear();
```
4. append() / push_back():在字符串末尾添加字符或字符串。
```
string str = "Hello";
str.append(" World"); // 或者使用 str += " World";
str.push_back('!'); // 在末尾添加单个字符
```
5. insert():在指定位置插入字符或字符串。
```
string str = "Hello";
str.insert(5, " C++"); // 在索引位置5插入字符串
```
6. erase():从字符串中删除指定范围的字符。
```
string str = "Hello, World!";
str.erase(5, 7); // 从索引位置5开始删除7个字符
```
7. replace():替换字符串中指定范围的字符或子串。
```
string str = "Hello, World!";
str.replace(7, 6, "C++"); // 从索引位置7开始替换6个字符为"C++"
```
8. substr():提取字符串的子串。
```
string str = "Hello, World!";
string sub = str.substr(7, 5); // 从索引位置7开始提取长度为5的子串
```
9. find() / rfind():查找子串在字符串中的位置(正向或反向)。
```
string str = "Hello, World!";
size_t pos = str.find("World"); // 或者使用 str.rfind("World");
```
10. compare():比较两个字符串。
```
string str1 = "Hello";
string str2 = "World";
int result = str1.compare(str2);
```
这些只是string类库的一部分函数,还有很多其他功能可以探索和使用。希望这些函数能帮到你!如果你有任何进一步的问题,请随时提问。
C++中string类模板的函数push_back()的具体实现
push_back()函数的具体实现是将一个元素添加到string的末尾,并增加string的大小。它首先检查是否有足够的容量来容纳新元素,如果没有,则调用reserve()函数进行重新分配内存空间,然后将新元素添加到string的末尾。如果容量已足够,则直接将新元素添加到string的末尾并增加大小。
相关推荐
![](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)