c++string取最后一个字符
时间: 2023-05-22 10:01:02 浏览: 152
可以使用strlen函数获取字符串长度,然后用字符串长度减1得到最后一个字符的下标,最后通过下标访问即可。示例代码如下:
```c
char str[] = "Hello World";
char last_char = str[strlen(str) - 1];
printf("The last character is %c\n", last_char);
```
输出结果为:
```
The last character is d
```
相关问题
C++获取string的最后一个字符
可以通过 string 类的成员函数 `back()` 获取 string 的最后一个字符。例如:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
char last = str.back();
std::cout << "The last character is " << last << std::endl;
return 0;
}
```
输出结果:
```
The last character is !
```
c++ string取文本右边n个字符
你可以使用 C++ 的 `substr` 函数来取文本右边的 n 个字符。具体的做法是先计算出要取的子串在原字符串中的起始位置,然后再调用 `substr` 函数来获取子串。代码示例如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello, world!";
int n = 5;
string sub = str.substr(str.size() - n, n);
cout << sub << endl;
return 0;
}
```
在上面的代码中,`str.size()` 函数返回了原字符串的长度,从而计算出了要取的子串的起始位置。然后调用 `substr` 函数来获取子串,存储在 `sub` 变量中。输出结果为 `orld!`,即原字符串的后 5 个字符。
相关推荐
![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)