當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 strpbrk()用法及代碼示例

此函數在字符串s1中找到與s2中指定的任何字符匹配的第一個字符(不包括終止null-characters)。

用法:
char *strpbrk(const char *s1, const char *s2)

參數:
s1:string to be scanned.
s2:string containing the characters to match.

返回值:
It returns a pointer to the character in s1 that 
matches one of the characters in s2, else returns NULL.
// C code to demonstrate the working of 
// strpbrk 
#include <stdio.h> 
#include <string.h> 
  
// Driver function 
int main() 
{ 
    // Declaring three strings 
    char s1[] = "geeksforgeeks"; 
    char s2[] = "app"; 
    char s3[] = "kite"; 
    char* r, *t; 
  
    // Checks for matching character 
    // no match found 
    r = strpbrk(s1, s2);  
    if (r != 0) 
        printf("First matching character:%c\n", *r); 
    else
        printf("Character not found"); 
  
    // Checks for matching character 
    // first match found at "e" 
    t = strpbrk(s1, s3); 
    if (t != 0) 
        printf("\nFirst matching character:%c\n", *t); 
    else
        printf("Character not found"); 
  
    return (0); 
}

輸出:

Character not found
First matching character:e

實際應用
此函數可用於彩票遊戲中帶有字母的字符串的人
獲勝者排名第一,即可以在第一人稱獲勝的任何地方使用。


// C code to demonstrate practical application 
// of strpbrk 
#include <stdio.h> 
#include <string.h> 
  
// Driver function 
int main() 
{ 
    // Initializing victory string 
    char s1[] = "victory"; 
  
    // Declaring lottery strings 
    char s2[] = "a23"; 
    char s3[] = "i22"; 
    char* r, *t; 
  
    // Use of strpbrk() 
    r = strpbrk(s1, s2); 
    t = strpbrk(s1, s3); 
  
    // Checks if player 1 has won lottery 
    if (r != 0) 
        printf("Congrats u have won"); 
    else
        printf("Better luck next time"); 
  
    // Checks if player 2 has won lottery 
    if (t != 0) 
        printf("\nCongrats u have won"); 
    else
        printf("Better luck next time"); 
  
    return (0); 
}

輸出:

Better luck next time
Congrats u have won



相關用法


注:本文由純淨天空篩選整理自 strpbrk() in C。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。