#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)
| 函數 | 搜尋目標 | 匹配邏輯 |
|---|---|---|
strchr | 單一字元 | 精確匹配該字元 |
strstr | 子字串 | 連續匹配整個子字串 |
strpbrk | 字元集合 | 匹配集合中任一字元 |
"\\/:*?\"<>|")。strcspn:計算 s1 開頭連續不包含 s2 中任一字元的長度(互補關係)。strspn:計算 s1 開頭連續包含 s2 中字元的長度。strtok:基於分隔符集合分割字串。