【问题标题】:Return a pointer to the last appearance of a character in a C-Style string (C++)返回指向 C 样式字符串 (C++) 中字符最后一次出现的指针
【发布时间】: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 匹配项。相反,您应该记住它的位置并继续前进。当你到达最后,然后返回保存的值。

标签: c++ string


【解决方案1】:

您可以通过获取指向字符串末尾的指针并递减字符串以搜索字符c 以及指向字符串开头的指针来知道在哪里停止循环:

const char *mystrrchr(const char *str, char c)
{
    int len = strlen(str);
    char *p = const_cast<char *>(&str[len-1]);
    char *stop = const_cast<char *>(&str[0]);
    while(p>=stop)
    {
        if(*p==c)
        {
            return p;
        }
        p--;
    }
    return nullptr;
}

【讨论】:

  • 感谢您的回复。但是,这个特殊问题需要 const char* str 和 char c 的参数。它也应该返回一个 const char* 。你将如何解决这个问题?
  • 非常感谢您的洞察力!我感谢您的解释。
猜你喜欢
  • 2019-06-15
  • 1970-01-01
  • 2021-02-14
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2013-02-16
  • 1970-01-01
相关资源
最近更新 更多