gpt4 book ai didi

c++ - 如何读取字符串中的最后一个字符

转载 作者:太空狗 更新时间:2023-10-29 20:33:03 27 4
gpt4 key购买 nike

我试图打印字符串的最后一个字符,例如 str[]="This is an example",我尝试用一​​些函数打印“example”的“e”,但没有一个函数像我期望。我知道在代码中写入最后一个字符的位置编号更简单,但就像在 strrchr 函数中一样,代码本身就可以工作。有类似的功能吗?

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int main ()
{
char str[] = "This is an example";
char * pch;
pch=strrchr(str,'s');

cout<<str<<endl;
cout<<"Last time 's' was found was in position: "<<pch-str+1<<endl;
cout<<"Last character in this example is "<<str[X];
return 0;
}

最佳答案

来自 the documentation for strrchr :

The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.

因此,strrchr(str, '\0')[-1] 将具有最后一个字符。请注意,只有当您确定 str 不为空时,这才是安全的。

关于c++ - 如何读取字符串中的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549389/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com