为了使用字符串或字符数组类型,C库提供了许多函数。 strchr()
函数是一个非常流行的函数,用于查找字符串或字符数组中给定字符的第一个匹配项。
null
语法和参数
作为 strchr()
提供第一次出现 对于给定的字符,它将返回指向第一个匹配项的指针。 我们还将提供正在搜索的字符串或字符数组以及要定位的图表。
char * strchr(const char*, int);
- `const char*`type是我们正在搜索的字符串或字符数组
- `int`是我们要搜索的字符值
返回值
返回值是指向给定 烧焦 .
带C的示例
我们将 从一个C示例开始,我们将在其中搜索 s
名为的字符串中的字符 str
.
/* strchr() function C example */#include#include int main (){ char str[] = "I really like the poftut.com"; char * pch; printf ("Looking for the 'l' character in "%s"...",str); pch=strchr(str,'l'); while (pch!=NULL) { printf ("'l' found at %d",pch-str+1); pch=strchr(pch+1,'s'); } return 0;}
我们将编译以下内容 gcc命令。
$ gcc strchr.c -o strchr_C_example
并调用示例可执行文件 strchr_C_example
.
$ ./strchr_C_example

C++实例
如前所述 strchr()
函数存在于C++程序设计语言库中。它的语法与 std
库作为静态函数。
//strchr() function C++ examples#include#include int main(){ const char *str = "I really like poftut.com"; char target = 'l'; const char *result = str; while ((result = std::strchr(result, target)) != NULL) { std::cout << "'l' found '" << target << "' starting at '" << result << "'"; ++result; }}
我们将编译一个具有以下内容的示例 克++ 命令。
$ g++ strchr_Cpp_example.cpp -o strchr_Cpp_example
然后我们将调用创建的示例binary strchru Cppu example
$ ./strchr_Cpp_example

© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END