C++ strchr()

strchr() 原型

const char* strchr( const char* str, int ch );
char* strchr( char* str, int ch );

strchr() 函数接受两个参数:strch。它在 str 指向的字符串中搜索字符 ch

它定义在 <cstring> 头文件中。

strchr() 参数

  • ptr:指向要搜索的以 null 结尾的字符串的指针
  • ch:要搜索的字符。

strchr() 返回值

如果找到该字符,strchr() 函数将返回指向 str 中该字符位置的指针,否则返回 null 指针。

示例:strchr() 函数如何工作

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char str[] = "Programming is easy.";
    char ch = 'r';
    
    if (strchr(str, ch))
        cout << ch << " is present \"" << str << "\"";
    else
        cout << ch << " is not present \"" << str << "\"";

    return 0;
}

运行程序后,输出将是

r is present "Programming is easy."
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战