我尝试为我的C ++类编写lastindexOf函数。在我尝试了2个星期后,我仍然无法使它工作。 起初,我试图遵循这篇文章的逻辑:CString find the last entry,但由于他们使用CString类而不是char类,我没有成功复制char类的代码。我也试过strstr,但我也没有运气。我很感激任何帮助 这是我到目前为止提出的代码:
#include
using namespace std;
int lastIndexOf(char *s, char target);
int main()
{
char input[50];
cin.getline(input, 50);
char h = h;
lastIndexOf(input, h);
return 0;
}
int lastIndexOf( char *s, char target)
{
int result = -1;
while (*s != '\0')
{
if (*s == target ){
return *s;
}}
return result;
}
答案 0 :(得分:2)
试试这个:
int lastIndexOf(const char * s, char target)
{
int ret = -1;
int curIdx = 0;
while(s[curIdx] != '\0')
{
if (s[curIdx] == target) ret = curIdx;
curIdx++;
}
return ret;
}