ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# C `strcspn()`函数 > 原文: [https://beginnersbook.com/2017/11/c-strcspn-function/](https://beginnersbook.com/2017/11/c-strcspn-function/) **`strcspn()`函数**在主字符串中扫描给定字符串,并返回主字符串中从开头到第一个匹配字符的字符数。 ## C `strcspn()`声明 ```c size_t strcspn(const char *str1, const char *str2) ``` `str1` - 要搜索的主字符串 `str2` - 在主字符串中搜索此字符串的字符,直到找到第一个匹配的字符 ## 函数`strcspn()`的返回值 此函数返回在找到第一个匹配字符之前,找到的主字符串中的字符数。 ## C 中的函数`strcspn()`例子 ```c #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; } ``` 输出: ```c The first matched char in string str1 is at: 7 ``` 我们在主字符串`str`中搜索的字符是`'d'`,`'x'`和`'z'`,第一个匹配的字符位于主字符串中的第 7 位。 #### 相关文章: 1. [C - `strcat()`函数](https://beginnersbook.com/2017/11/c-strcat-function-with-example/) 2. [C - `strchr()`函数](https://beginnersbook.com/2017/11/c-strchr-function/) 3. [C - `strcmp()`函数](https://beginnersbook.com/2017/11/c-strcmp-function/) 4. [C - `strcpy()`函数](https://beginnersbook.com/2017/11/c-strcpy-function/)