strcspn()函数在主字符串中扫描给定字符串,并返回主字符串中从开头到第一个匹配字符的字符数。
C strcspn()声明
size_t strcspn(const char *str1, const char *str2)
str1 – 要搜索的主字符串
str2 – 在主字符串中搜索此字符串的字符,直到找到第一个匹配的字符
函数strcspn()的返回值
此函数返回在找到第一个匹配字符之前,找到的主字符串中的字符数。
C 中的函数strcspn()例子
#include <stdio.h>
#include <string.h>
int main () {
const char str[20] = "aabbccddeeff";
const char searchString[10] = "dxz";
int loc;
/* This function returns the number of characters present in the main string
* from beginning till the first matched character is found
*/
loc = strcspn(str, searchString);
printf("The first matched char in string str1 is at: %d", (loc+1));
return 0;
}
输出:
The first matched char in string str1 is at: 7
我们在主字符串str中搜索的字符是'd','x'和'z',第一个匹配的字符位于主字符串中的第 7 位。
极客教程