如何在C++中实现自定义的strrchr功能

   2024-10-01 9920
核心提示:以下是一个示例代码,演示了如何在C++中实现自定义的strrchr功能:#include iostreamconst char* custom_strrchr(const char* st

以下是一个示例代码,演示了如何在C++中实现自定义的strrchr功能:

#include <iostream>const char* custom_strrchr(const char* str, char ch) {    const char* result = nullptr;    while (*str) {        if (*str == ch) {            result = str;        }        str++;    }    return result;}int main() {    const char* str = "hello world";    char ch = 'o';        const char* result = custom_strrchr(str, ch);        if (result != nullptr) {        std::cout << "Last occurrence of '" << ch << "' in '" << str << "' is at index " << result - str << std::endl;    } else {        std::cout << "'" << ch << "' not found in '" << str << "'" << std::endl;    }        return 0;}

在这个示例中,custom_strrchr函数接受一个字符串和一个字符作为参数,在字符串中查找字符的最后一个匹配,并返回指向该位置的指针。在main函数中,我们调用custom_strrchr函数来查找字符串中字符'o'的最后一个匹配,并输出结果。

当我们运行这段代码时,将得到以下输出:

Last occurrence of 'o' in 'hello world' is at index 7

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号