C++ strchr函数的返回值处理技巧

avatar
作者
筋斗云
阅读量:2

strchr函数的作用是在一个字符串中查找指定字符的第一次出现位置,并返回该位置的指针。如果找到指定字符,则返回指向该字符的指针;如果未找到指定字符,则返回空指针。

在使用strchr函数时,可以通过判断返回值来判断是否找到了指定字符,进而进行相应的处理。下面是一个示例代码:

#include <iostream> #include <cstring>  int main() {     const char* str = "Hello, World!";     const char ch = 'o';          const char* pos = strchr(str, ch);          if (pos != nullptr) {         std::cout << "Found character '" << ch << "' at position: " << pos - str << std::endl;     } else {         std::cout << "Character '" << ch << "' not found in the string." << std::endl;     }          return 0; } 

在上面的代码中,首先定义了一个字符串和一个要查找的字符。然后使用strchr函数在字符串中查找指定字符,并将返回值赋给pos指针。最后通过判断pos是否为空指针来确定是否找到了指定字符,并输出相应的结果。

需要注意的是,在判断返回值时使用了nullptr来判断是否为空指针,这是C++11标准引入的nullptr关键字,用于表示空指针。在早期的C++标准中,可以使用NULL来表示空指针。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!