首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 標準庫函數詳解:strpbrk — 尋找字元集合中任一字元首次出現位置

     編輯:關於C語言

函數原型

#include <string.h>
char *strpbrk(const char *s1, const char *s2);

功能描述

在字串 s1 中尋找字串 s2 中任一字元首次出現的位置。搜尋範圍不包含結束符 \\0。

參數說明

  • s1:目標搜尋字串。
  • s2:包含待匹配字元的字元集合(視為一個集合,而非子字串)。

返回值

  • 成功:返回指向 s1 中首個匹配字元的指標。
  • 失敗:若 s1 中無任何 s2 包含的字元,返回 NULL。

範例程式碼

// strpbrk_demo.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *str1 = "Welcome To Beijing";
    const char *set1 = "BIT";      // 尋找 B, I, T 中任一字元
    const char *set2 = "Da";       // 尋找 D, a 中任一字元
    char *pos;

    // 範例 1:匹配 'B' (位置 11), 'I' (位置 15), 'T' (位置 16) -> 最早是 'B'
    pos = strpbrk(str1, set1);
    if (pos) {
        printf("集合 \"%s\" 中字元首次出現於: %s (索引 %ld)\n", set1, pos, pos - str1);
    } else {
        printf("集合 \"%s\" 中無字元匹配\n", set1);
    }

    // 範例 2:匹配 'a' (位置 1 - Welcome 的 a? 不,Welcome 無 a。Beijing 有 a? 無。To 無。實際無匹配)
    // 修正:Welcome To Beijing 中無 'D' 或 'a' (大小寫敏感)
    pos = strpbrk(str1, set2);
    if (pos) {
        printf("集合 \"%s\" 中字元首次出現於: %s\n", set2, pos);
    } else {
        printf("集合 \"%s\" 中無字元匹配 (區分大小寫)\n", set2);
    }

    // 範例 3:尋找母音字母
    const char *vowels = "aeiouAEIOU";
    pos = strpbrk(str1, vowels);
    if (pos) printf("首個母音字母: %c (位置 %ld)\n", *pos, pos - str1);

    return 0;
}

執行結果

集合 "BIT" 中字元首次出現於: Beijing (索引 11)
集合 "Da" 中無字元匹配 (區分大小寫)
首個母音字母: e (位置 1)

strpbrk vs strstr vs strchr

函數搜尋目標匹配邏輯
strchr單一字元精確匹配該字元
strstr子字串連續匹配整個子字串
strpbrk字元集合匹配集合中任一字元

應用場景

  • **輸入驗證**:快速檢查字串是否包含非法字元(如檔名保留字元 "\\/:*?\"<>|")。
  • **分詞預處理**:尋找分隔符集合(空白、標點、逗號)中的第一個分隔符位置。
  • **字元分類統計**:配合迴圈遍歷統計特定字元集合出現次數。

相關函數

  • strcspn:計算 s1 開頭連續不包含 s2 中任一字元的長度(互補關係)。
  • strspn:計算 s1 開頭連續包含 s2 中字元的長度。
  • strtok:基於分隔符集合分割字串。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved