strpbrk
- Locate characters in string,Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.
- The search does not include the terminating null-characters of either strings, but ends there.
- 在 dest 所指向的空終止位元組串中,掃描來自 breakset 所指向的空終止位元組串的任何字元,並返回指向該字元的指標。
- 檢索字串 dest 中第一個匹配字串 breakset 中字元的字元,不包含空結束字元。也就是說,依次檢驗字串 dest 中的字元,當被檢驗字元在字串 breakset 中也包含時,則停止檢驗,並返回該字元位置。
- 若 dest 或 breakset 不是指向空終止位元組字串的指標則行為未定義。
char* strpbrk( const char* dest, const char* breakset );
Parameters
dest
- C string to be scanned.
- 指向要分析的空終止位元組字串的指標
breakset
- C string containing the characters to match.
- 指向含要搜尋的字元的空終止位元組字串的指標
Return Value
- A pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if none of the characters of str2 is found in str1 before the terminating null-character.If none of the characters of str2 is present in str1, a null pointer is returned.
- 指向 dest 中首個亦在 breakset 中的字元的指標,或若這種字元不存在則為空指標。
- 該函式返回 dest 中第一個匹配字串 breakset 中字元的字元數,如果未找到字元則返回 NULL。
名稱代表“字串指標打斷 (string pointer break) ”,因為它返回指向首個分隔符(“打斷”)的指標。
Example
//
// Created by zhangrongxiang on 2018/2/6 11:18
// File strpbrk
//
#include <stdio.h>
#include <string.h>
//依次檢驗字串 str1 中的字元,當被檢驗字元在字串 str2 中也包含時,則停止檢驗,並返回該字元位置。
//檢索字串 str1 中第一個匹配字串 str2 中字元的字元,不包含空結束字元。
int main() {
int i = 0;
const char str1[] = "abcde2fghi3jk4l";
const char str2[] = "34";
const char *str3 = "Life is short,I use C";
char *ret;
ret = strpbrk(str1, str2);
if (ret) {
printf("Number one is : %c
", *ret);//3
} else {
printf("No");
}
ret = strpbrk(str1, str3);
if (ret) {
printf("Number one is : %c
", *ret);//e
} else {
printf("No");
}
printf("
");
size_t len = strlen(str1);
char *ch = 0;
int index = 0;
char all[20] = {0};
//獲取兩個字串的字元交集
for (; i < len; ++i) {
ret = strpbrk((str1 + sizeof(char) * (index + 1)), str3);
if (ret) {
ch = strrchr(str1, *ret);
index = (int) (ch - str1);
printf("Number one is : %c
", *ret);
all[i] = *ret;
} else {
printf("No");
}
}
printf("
");
for (i = 0; i < 20; ++i) {
if (all[i] == 0)
break;
printf("%c ", all[i]); //e f h i
}
printf("
");
//單詞統計
const char *str = "hello world, friend of mine!";
const char *sep = " ,!";
unsigned int cnt = 0;
do {
str = strpbrk(str, sep); // 尋找分隔符
// printf("%s
",str);
if (str){
str += strspn(str, sep); // 跳過分隔符
printf("%s
",str);
}
++cnt; // 增加詞計數
} while (str && *str);
printf("There are %d words
", cnt); // 5
return 0;
}