【发布时间】:2013-10-12 23:23:34
【问题描述】:
我尝试为我的 C++ 类编写 lastindexOf 函数。在我尝试了 2 周后,我仍然无法让它工作。
起初,我试图遵循这篇文章中的逻辑:CString find the last entry,但由于他们使用 CString 类而不是 char 类,我没有成功复制 char 类的代码。我也尝试了 strstr,但我也没有运气。我将不胜感激。
这是我到目前为止提出的代码:
#包括
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;
}
【问题讨论】:
-
您正在寻找
strchr()。顺便说一句,您的错误是您没有增加while循环的循环计数器,因此它将是无限的。 -
对于 lastIndexOf(),strrchr() 可能会更好。