如何在C++中实现自定义的strrchr功能
导读:以下是一个示例代码,演示了如何在C++中实现自定义的strrchr功能: #include <iostream> const char* custom_strrchr(const char* str, char ch {...
以下是一个示例代码,演示了如何在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
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何在C++中实现自定义的strrchr功能
本文地址: https://pptw.com/jishu/694134.html
