C ++中的strpbrk()

这是C ++中的字符串函数,它接收两个字符串,并在string1中查找string2的任何字符的第一个匹配项。如果有,则返回指向string1中字符的指针,否则返回NULL。这不适用于终止NULL字符。

的语法strpbrk()如下-

char *strpbrk(const char *str1, const char *str2)

在以上语法中,strpbrk()将指针返回到str1中与str2中任何字符匹配的第一个字符。

演示程序strpbrk()如下。

示例

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[20] = "aeroplane";
   char str2[20] = "fun";
   char *c;
   c = strpbrk(str1, str2);
   if (c != 0)
   cout<<"First matching character in str1 is "<< *c <<" at position "<< c-str1+1;
   else
   printf("Character not found");
   return 0;
}

输出结果

First matching character in str1 is n at position 8

在上面的程序中,首先定义了两个字符串str1和str2。指向str1中返回的字符的指针strpbrk()存储在c中。如果c的值不为0,则显示字符及其在str1中的位置。否则,字符在str1中不存在。下面的代码片段对此进行了演示。

char str1[20] = "aeroplane";
char str2[20] = "fun";
char *c;
c = strpbrk(str1, str2);
if (c != 0)
cout<<"First matching character in str1 is "<<*c <<" at position "<< c-str1+1;
else
printf("Character not found");