c++

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

小樊
83
2024-08-15 11:11:38
栏目: 编程语言

以下是一个示例代码,演示了如何在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

0
看了该问题的人还看了