C String Functions - C strpbrk






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

Finds the first character in the string str1 that matches any character specified in str2.

A pointer to the location of this character is returned.

A null pointer is returned if no character in str2 exists in str1.

Prototype

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

Parameter

This function has the following parameter.

str1
C string to be scanned.
str2
C string containing the characters to match.

Return

A pointer to the first occurrence in str1 of any characters from str2, or a null pointer if none of the characters of str2 is found in str1.

If none of the characters of str2 is found in str1, a null pointer is returned.





Example


#include <stdio.h>
#include <string.h>
//from w  w w.ja  v  a  2  s .  c o m
int main (){
  char str[] = "This is a test";
  char key[] = "aeiou";
  char * pch;
  printf ("Vowels in '%s': ",str);
  pch = strpbrk (str, key);
  while (pch != NULL){
    printf ("%c " , *pch);
    pch = strpbrk (pch+1,key);
  }
  printf ("\n");
  return 0;
}        

The code above generates the following result.





Example 2


#include<string.h> 
#include<stdio.h> 
//from w  w  w.j av  a  2 s. com
int main(void) { 
  char string[]="this is a test!"; 
  char *string_ptr; 

  while((string_ptr=strpbrk(string," "))!=NULL) 
    *string_ptr='-'; 

  printf("New string is \"%s\".\n",string); 
  return 0; 
} 

The code above generates the following result.

Example 3


#include <stdio.h>
#include <string.h>
 /*from   w  ww.  jav a  2 s  . c  o  m*/
int main(void){
    const char* str = "this is a test,!";
    const char* sep = " ,!";
 
    unsigned int cnt = 0;
    do {
       str = strpbrk(str, sep); // find separator
       if(str) str += strspn(str, sep); // skip separator
       ++cnt; // increment word count
    } while(str && *str);
 
    printf("There are %d words\n", cnt);
}

The code above generates the following result.