【发布时间】:2016-11-13 20:41:56
【问题描述】:
返回一个指向 c 的最后出现的指针 出现在 s 中,如果 c 没有出现在 s 中,则为 nullptr (0)。
#include <string>
#include <iostream>
#include <cassert>
using namespace std;
const char* myStrRChr(const char* s, char c)
{
int curIdx = 0;
char last;
while (s[curIdx] != '\0')
{
if (s[curIdx] == c)
last = s[curIdx];
curIdx++;
}
if (s[curIdx] == c)
return last;
else
// return '\0', nullptr, NULL
return "";
}
int main()
{
char cstr[50] = "Abadabadoo!";
char buf[10];
const char * cat = "cat";
char dog[] = "Labradoodle";
cout << "\nmyStrRChr(cstr, 'a') expects adoo!" << endl;
cout << " -- " << myStrRChr(cstr, 'a') << endl;
return 0;
}
此代码返回“adabadoo!”。我不知道如何获取“char c”的最后一个实例。
【问题讨论】:
-
你需要一个指针而不是索引?
-
你需要找出你做错了什么。
-
while循环是无限的。你确定这是你使用的代码吗? -
@PaulMcKenzie,忘记添加了。已编辑。
-
您返回找到的 first 匹配项。相反,您应该记住它的位置并继续前进。当你到达最后,然后返回保存的值。