C library provides a lot of functions in order to use string or char array types. strchr()
function is a very popular function which is used to find the first occurrence of a given character in a string or char array.
C库提供了许多功能以使用字符串或char数组类型。 strchr()
函数是一个非常流行的函数,用于查找字符串或char数组中给定字符的首次出现。
语法和参数 (Syntax and Parameters)
As strchr()
provides the first occurrence of the given char it will return a pointer to the first occurrence. We will also provide the string or char array we are searching in and the chart we want to locate.
由于strchr()
提供了给定char的第一个匹配项,因此它将返回一个指向第一个匹配项的指针。 我们还将提供要搜索的字符串或char数组以及要查找的图表。
char * strchr(const char*, int);
- `const char*` type is the string or char array we are searching in const char *类型是我们要搜索的字符串或char数组
- `int` is the char we are searching for value“ int”是我们在寻找价值的字符
返回值(Return Value)
The return value is a char pointer to the first occurrence of the given char .
返回值是给定char首次出现的char指针。
C的例子 (Example with C)
We will start with a C example where we will search the s
character in the string named str
.
我们将从一个C示例开始,在该示例中,我们将在名为str
的字符串中搜索s
字符。
/* strchr() function C example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "I really like the poftut.com";
char * pch;
printf ("Looking for the 'l' character in \"%s\"...\n",str);
pch=strchr(str,'l');
while (pch!=NULL)
{
printf ("'l' found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
We will compile with the following gcc command.
我们将使用以下gcc命令进行编译。
$ gcc strchr.c -o strchr_C_example
and call the example executable strchr_C_example
.
并调用示例可执行文件strchr_C_example
。
$ ./strchr_C_example

C ++示例(Example with C++)
As stated previously strchr()
function exist in C++ programming language standard library. It has the same syntax where provided by std
library as a static function.
如前所述, strchr()
函数存在于C ++编程语言标准库中。 它具有与std
库提供的静态函数相同的语法。
//strchr() function C++ examples
#include <iostream>
#include <cstring>
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 << "'\n";
++result;
}
}
We will compile an example with the following g++ command.
我们将使用以下g ++命令来编译示例。
$ g++ strchr_Cpp_example.cpp -o strchr_Cpp_example
and then we will call created example binary strchr_Cpp_example
然后我们将调用创建的示例二进制strchr_Cpp_example
$ ./strchr_Cpp_example

翻译自: https://www.poftut.com/strchr-find-character-in-a-string-c-and-cpp-tutorial-with-examples/